using statement for background worker
I have been looking over several examples of backgroundworkers and I ran across code that looks similar to this
public class MyClass
{
public MyClass()
{
using(BackgroundWorker _Worker = new BackgroundWorker { WorkerReportsProgress = true})
{
_Worker.DoWork += (s, args) =>
{
...
};
}
_Worker.RunWorkerAsync();
}
}
I have not been using the "using" statment in my code like this. I ran across som开发者_JS百科ething similar while using the Code Rush trial, which made me come back to this code and question if i should be doing this or not. Please help me understand if/why this would be best practice. Thanks.
Actually BackgroundWorker
does not need to be disposed, see here. So there is no need to have the using
clause
Using the using
keyword like that simply handles dispose for you. Without it, you'd be constantly writing try / catch / finally
blocks in order to make sure objects implementing IDisposable were disposed properly.
Also note that you can put multiple declarations in a using statement, if you have multiple objects that need to be disposed:
using (Font font3 = new Font("Arial", 10.0f),
font4 = new Font("Arial", 10.0f))
{
// Use font3 and font4.
}
Here's the MSDN documentation on it.
The using
statement defines a scope that outside of which objects will be disposed. So it is just a convention by which the resources are disposed of automatically. From MSDN,
The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.
It is perfectly acceptable in your scenario.
The using statement takes place of surrounding your code with a try/catch block. But not everything can use the using statement; only objects that implement Dispose() can.
精彩评论