471,319 Members | 1,721 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,319 software developers and data experts.

Calling BackgroundWorker synchronous

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!

Feb 14 '06 #1
3 9628
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

Feb 14 '06 #2
Hello, Pro1712!

Why do you need such a behavior, if you need sycnhrounous behavior then you can simply call DoWork method...

--
Regards, Vadym Stetsyak
www: http://vadmyst.blogspot.com
Feb 14 '06 #3
Hello, bo*********@gmail.com!

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
Feb 14 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by Ulf | last post: by
14 posts views Thread by =?Utf-8?B?SXNobWFlbA==?= | last post: by
reply views Thread by Chris | last post: by
9 posts views Thread by Pubs | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.