Is there a better deterministic disposal pattern than nested “using”s?

前端 未结 10 1432
难免孤独
难免孤独 2021-02-18 18:23

In C#, if I want to deterministically clean up non-managed resources, I can use the \"using\" keyword. But for multiple dependent objects, this ends up nesting further and furt

10条回答
  •  无人共我
    2021-02-18 18:42

    I have implemented solutions like Michael Meadows's before, but his StreamWrapper code doesn't take into account if the Dispose() methods called on the member variables throw an exception for one reason or another, the subsequent Dispose()es will not be called and resources could dangle. The safer way for that one to work is:

            var exceptions = new List();
    
            try
            {
                this.sr.Dispose();
            }
            catch (Exception ex)
            {
                exceptions.Add(ex);
            }
    
            try
            {
                this.bs.Dispose();
            }
            catch (Exception ex)
            {
                exceptions.Add(ex);
            }
    
            try
            {
                this.fs.Dispose();
            }
            catch (Exception ex)
            {
                exceptions.Add(ex);
            }
    
            if (exceptions.Count > 0)
            {
                throw new AggregateException(exceptions);
            }
        }
    

提交回复
热议问题