Run BackgroundWorker after completing another

I want to start BackgroundWorker after completing another. I'm not sure how to write code for it, so I really have nothing to show.

I thought about writing it to RunWorkerCompleted , but this seems like the wrong place to enter logic to start another worker.

Where and how should I do this?

Basically, I want to use the same employee, but do something else. As in step 1, it analyzes the data from the files and in step 2, after completing step 1, it must write the analyzed data from memory to the database.

+4
source share
4 answers

If you use a third-party library for scheduling tasks, you can check Quartz.NET and the listener mechanism here http://quartznet.sourceforge.net/tutorial/lesson_7.html . If you want to implement it yourself, I would use one BackgroundWorker , which would complete a set of tasks organized in a chain of responsibility chain, you can read more about this template here http://dofactory.com/Patterns/PatternChain.aspx .

+1
source

Instead, you can use the .NET 4.0 Task class, and then do more work with Task.ContinueWith .

+4
source

It is probably best to use two different BackgroundWorker components. Run the second in the RunWorkerCompleted event RunWorkerCompleted for the first. This seems like a very reasonable way to do something. Just don't try to do this with a single BackgroundWorker .

As Tudor mentioned , you can use Task , but then you lose the convenience of BackgroundWorker , with its familiar event-oriented interface, etc.

+3
source

From your description, it seems that the steps are connected and sequential, so I would implement them as a single BGW, where DoWork performs both steps with a ReportProgress call between the parsing step and the writing step to the database.

You can then handle the ProgressChanged event, which is executed in the user interface thread, to execute any logic after the parsing stage is complete, knowing that the worker is already writing to the database.

ReportProgress takes an integer to determine the percentage of completion of the background task and an optional user object. Therefore, in your ProgressChanged handler, you need to have logic to interpret this progress information. In this case, as a two-step job, you can just call ReportProgress(50) .

+3
source

Source: https://habr.com/ru/post/1388957/


All Articles