BackgroundWorker and Threads

后端 未结 6 2432
渐次进展
渐次进展 2021-02-15 11:19

What are the pros and cons in using the either for achieving a given task.

The million dollar question is which one to use and when?

Many Thanks.

6条回答
  •  萌比男神i
    2021-02-15 11:30

    The BackgroundWorker class simply provides events that are switched to the context of the UI thread for you, but don't be confused; the DoWork event (which is where you actually, well, do the work) is still executed in the context of another thread (as that's the point of the whole thing) and performing any kind of UI interaction or update there will throw an exception at best, and crash at worst. The BackgroundWorker should be used on forms when you're trying to do something that requires a UI update and whose scope doesn't extend beyond that of the form. For other background operations, consider either using the ThreadPool (for short-lived operations) or creating your own Thread.

    The BackgroundWorker provides convenience with the ProgressChanged event, but don't get too comfortable and start doing UI updates in DoWork.

提交回复
热议问题