views:

125

answers:

4

Hi,

I have a method which is worked asynchronous by a BackgroundWorker. Within this method, some code loops infinitly with an interval of 1000 ms.

Within this code, depending on some value, an event is dispatched. As far as I have understood this, this event runs in the same thread as the code from which it has been raised.

But what I want is, that this event runs in the same thread as the object which holds the BackgroundWorker. How do I achive this?

+4  A: 

You would be better off using a Timer to schedule recurring events. If this is a Windows Forms application (which I'll assume it is since you want to run it in the context of the "owning" thread) you should use a System.Windows.Forms.Timer instance.

Adam Robinson
+1 for Timer it is simple and easy to use.
Sergey Mirvoda
Timers don't run elapsed events in the same context of the owning thread do they? Their elapsed events run in separate threads.
Will
@Will: A `System.Threading.Timer` behaves as you describe. `System.Windows.Forms.Timer` events run on the UI thread.
Adam Robinson
Hi, I thought of using the Timer class, too. Are there any performance issues compared to the backgroundWorker?
Thomas
@Thomas: No; in fact, what you're attempting to do isn't really a good candidate for the `BackgroundWorker` class, as it uses the `ThreadPool`.
Adam Robinson
@Will: No, the `System.Windows.Forms.Timer` *does* raise its `Tick` event on the owning thread. You might be thinking of `System.Threading.Timer`.
Dan Tao
Thanks a lot for all the quick help.. I will replace the BackgroundWorker with a Timer.. seems to be more logical to me anyway..
Thomas
+2  A: 

Depending on your domain and application, you can use the ProgressChanged event (and ReportProgress method), which runs in the thread you want.

Jon Seigel
A: 

Is your 'receiving' thread the GUI thread? If so then look at Control.Invoke() or Control.BeginInvoke(). Assuming it is your form, or some control on your form, that is handling this periodic event then you should be able to do this.

Andy
yeah.. no ^^ Invoke would be perfect, but the Thread is no GUI Thread at all.. tried to implement ISynchronizeInvoke, too.. but it was too complicated since I thought there must be an easier way.. using a timer now and it works like a charm ;)
Thomas
Yeah, it only works for the GUI thread as it's already got a message loop. You'd have to do your own message loop in other threads. Not gonna be simple!
Andy
A: 

You may need to take a look at the System.Threading.SynchronizationContext which can be used to post events back to the BackgroundWorker Holder.

Islam Ibrahim