Can anyone explain the difference between Delegates and BackgroundWorker?In which case Backgroundworker is more efficient than Delegate?Since we are having asynchronous delegate what is the need to use BackGroungWorker.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
I have a brief comparison of
BackgroundWorker
, asynchronous delegates, and other approaches on my blog (from the perspective of doing background operations).BackgroundWorker
has these advantages:BackgroundWorker
whoseWorkerSupportsProgress
property is true may report progress. TheDoWork
delegate may invokeReportProgress
, which causes theProgressChanged
event to fire.BackgroundWorker.CancelAsync
. This causes theBackgroundWorker.CancellationPending
property to become true. TheDoWork
delegate should monitor that property (checking it on a regular basis), and setDoWorkEventArgs.Cancel
to true and return if the operation is cancelled. TheRunWorkerCompleted
delegate detects a cancelled result by checkingRunWorkerCompletedEventArgs.Cancelled
.ProgressChanged
andRunWorkerCompleted
events are synchronized to theSynchronizationContext
that was in place whenRunWorkerAsync
was called.Asynchronous delegates have this advantage:
In conclusion, I recommend using
Task<TResult>
instead of eitherBackgroundWorker
or asynchronous delegates.BackgroundWorker
:Delegate
:The question of which one to use has nothing to do with efficiency.
BackgroundWorker
is a wrapper that simplifies working with threads, you can use async delegates just as well, but managing them correctly is much more difficult. Or, from MSDN:The background worker is primarily for UI work where you need to easily run a task on a background thread and provide progress updates to the screen.
One advantage is it marshalls its callbacks to the UI thread for you so you don't need to check if InvokeRequired etc.
Delegates are a more general mechanism for passing functions as arguments and by executing them asynchronously they give you an easy way of running those methods on another thread.
Background worker is an abstraction to help you execute an operation on a separate thread.
Delegates don't really start separate threads - they are a type for referring to methods.
But what you are probably interested in is when you should use asynchronous methods instead of using background worker. I have not much experience in this, but Anders Hejlsberg talked about it some in his PDC session on the Future of C#.
The message I got was that in some circumstances asynchronous methods would be preferable because of lower complexity. The UI thread would still be blocked, but not for so long that it mattered.