Calling BackgroundWorker synchronous

P

Pro1712

Hi,

this may be a stupid question:
How can I can call the DoWork-function of a BackgroundWorker
synchronous?
Or in other words:
How can I extend the BackgroundWorker class with a function
RunWorkerSync()?


I want to write a class that I can call functions synchronous and
asynchronous.
e.g.
This is the code for running the function DoWork asynchronous
(incomplete);

void TestAsync()
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += DoWork;
worker.RunWorkerCompleted += RunWorkerCompleted;
...
worker.RunWorkerAsync(Param);
...
}

void DoWork(object sender, DoWorkEventArgs e)
{
Object Param = (Object) e.Argument;

// do something

e.Result = something;
}

void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
m_Result = (Object) e.Result;
}



This is the code for running synchronous (incomplete);
void TestSync()
{
// call synchronous
m_Result = DoWork(Object Param);
}


How can I combime this?


Thanks for your help!
 
B

bobbychopra

If you don't mind polling to check if the process is completed, then
define your own class which inherits from BackgroundWorker

public class MyBackgroundWorker : BackgroundWorker
{
public DoWorkSynchronous(object Param)
{
DoWork(Param);

while(IsBusy)
sleep(100);

return;
}
}
DISCLAIMER: Code for display purposes, not tested


I hope this helped.

Sincerely,
Bobby
 
V

Vadym Stetsyak

Hello, (e-mail address removed)!

b> public class MyBackgroundWorker : BackgroundWorker
b> {
b> public DoWorkSynchronous(object Param)
b> {
b> DoWork(Param);

b> while(IsBusy)
b> sleep(100);

b> return;
b> }
b> }
b> DISCLAIMER: Code for display purposes, not tested

b> I hope this helped.

IMO it is better to wait and not to poll.

public DoWorkSynchronous(object Param)
{
DoWork(Param);

internalSyncEvent.WaitOne(timeout, false);
return;
}

DoWork(param)
{
//do work
internalSyncEvent.Set(); //signal that the work is done
}

--
Regards, Vadym Stetsyak
www: http://vadmyst.blogspot.com
 

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