views:

2457

answers:

5

Events are synchronous in C#. I have this application where my main form starts a thread with a loop in it that listens to a stream. When something comes along on the stream an event is fired from the loop to the main form.

If the main form is slow or shows a messagebox or something the loop will be suspended. What is the best way around this? By using a callback and invoke on the main form?

+7  A: 

Since you're using a form, the easier way is to use the BackgroundWorker component.

The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution.

John
I must agree, a BackgroundWorker is the nicest and cleanest way.
Davy Landman
+1  A: 

Hmmm, I've used different scenarios that depended on what I needed at the time.

I believe the BeginInvoke would probably be the easiest to code since you're almost there. Either way you should be using Invoke already, so just changing to BeginInvoke. Using a callback on a separate thread will accomplish the same thing (as long as you use the threadpool to queue up the callback) as using BeginInvoke.

Sam
This fitted the best with my application, throwing the loop in a backgroundworker doesn't quite fit the way I want to handle this.
Niklas Winde
+1  A: 

Events are just delegates, so use BeginInvoke. (see Making Asynchronous Method Calls in the .NET Environment)

Davy Landman
A: 

You have a few options, as already detailed, but in my experience, you're better off leaving delegates and BeginInvoke, and using BackgroundWorker instead (v2.0+), as it is easier to use and also allows you to interact with the main form on the thread's completion. All in all a very weel implemented solution, I have found.

Raithlin
A: 

System.ComponentModel.BackgroundWorker is indeed a good starting point. It will do your asynchronous work, give you notifications of important events, and has ways to better integrate with your forms.

For example, you can activate progress notifications by registering a handler for the ProgressChanged event. (which is highly recommended if you have a long, asynchronous process and you don't want your user to think the application froze)

ee