Background worker

C

csharpula csharp

Hello,
Can you please tell me if I should use the background worker in the
following way:
if (worker.IsBusy)
worker.CancelAsync(); (or I can avoid this if)?

And in case I want to restart the background worker ,should I do it this
way?
worker.RunWorkerAsync();

Thank u !
 
M

Marc Gravell

Regards the "if(worker.IsBusy)", I imagine that yes, you can drop the
if and just call CancelAsync. I say this because if you *had* to test
IsBusy, you'd already have a race-condition (since the other thread
could complete between the IsBusy and CancelAsync calls). However,
including this test doesn't do much harm.

Regards restarting, that sounds about right - but in this case you
*do* want to check that it isn't already running since it throws an
exception if you try to use it twice at once. There is no race
condition here since it can only become "safer" (if you see what I
mean).

Mar
 
P

Peter Ritchie [C# MVP]

You can "restart" the background worker by calling RunWorkerAsync, but you
won't be able to call that until after you receive the RunWorkerCompleted
event. Until you get that event you'll get an InvalidOperationException.
 
C

Creativ

A question:

ThreadPool also provides the async execution of tasks. So when should
I use ThreadPool and when BackgroundWorker? What's the difference
between them?
 
P

Peter Duniho

A question:

ThreadPool also provides the async execution of tasks. So when should
I use ThreadPool and when BackgroundWorker? What's the difference
between them?

BackgroundWorker uses the ThreadPool. It adds to that the ability to deal
with cross-thread issues, by providing an event-driven model for using
it. In particular, the notification events like ProgressChanged and
RunWorkerCompleted will be raised on the same thread that created the
BackgroundWorker instance. This means you can use the BackgroundWorker
class from a Form instance, creating it on the main GUI thread for the
Form and not having to worry about using Invoke() or BeginInvoke() to call
code that accesses the Form instance itself.

If your background thread code needs to communicate with a GUI object like
a Form- or Control-derived class, then the BackgroundWorker class provides
a nice simplified API to do that.

Pete
 
D

DaveL

i use background worker quite abit, and never use CancelAsync
In my case each thread must complete..whether successful or a error occurred
, they complete

if your case is long running threads and you have a UI
I would set a cancel property in the class doing the work to cancel the job
that it is doing.. therefore the worker thread always complets
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top