1

Is there any difference between dropping a BackgroundWorker component on form using designer, or just creating it on code as an object variable. eg ...

BackgroundWorker bgwrkr = new BackgroundWorker();

I would prefer to create in code.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • 3
    Its the same, check the yourform.designer.cs file and you will find there the auto-generate code declaration of the background worker object, something like `private System.ComponentModel.BackgroundWorker backgroundWorker1;` – Jonathan Applebaum Sep 10 '20 at 15:35
  • Or simply get rid of it for good, https://blog.lextudio.com/how-to-replace-backgroundworker-with-async-await-and-tasks-80d7c8ed89dc – Lex Li Sep 10 '20 at 16:41
  • Don't forget to Dispose the worker. – Alexander Petrov Sep 10 '20 at 16:59
  • 1
    [Why should I insert a non-UI Windows.Forms component from the designer?](https://stackoverflow.com/a/32801463/3110834) – Reza Aghaei Sep 10 '20 at 18:54
  • @LexLi to be honest with you, I find the whole task ecosystem really overly complicated. I just prefer the amazingly-simple background worker. You create it, you start it, and you get an event when it's finished. You can also report progress, and cancel it. Love it. Why use anything else. – Excelnoobster Sep 11 '20 at 10:14
  • @AlexanderPetrov I don't think it's necessary: https://stackoverflow.com/questions/2542326/proper-way-to-dispose-of-a-backgroundworker – Excelnoobster Sep 11 '20 at 10:16
  • 1
    @Excelnoobster The linked [answer](https://stackoverflow.com/questions/2542326/proper-way-to-dispose-of-a-backgroundworker) has a point, but in general you should ignore implementation details and if you find out a class is `IDisposable`, you should dispose it. As I explained in my linked [answer](https://stackoverflow.com/a/32801463/3110834) When you drop the component on `Form` the designer generates code and takes care of dispose, but if you create the component instance yourself, you need to take care of dispose yourself. – Reza Aghaei Sep 11 '20 at 17:58

1 Answers1

3

When you drop a component (e.g. the BackgroundWorker or the Timer) on a form, you can set its properties and wire up event handlers in the properties window. The WinForms designer then creates the initialization code for you. Otherwise you must do all this manually.

But there is no difference in the functionality for these two variants. Many components do not need to be dropped on a form and they do not have any relation to the form. You can also instantiate these components in any other class or struct.


But there are also other types of components like ToolTip or ErrorProvider that add functionality to a Form or to a UserControl and make no sense in other classes.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188