Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to make events asynchronous in C#

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?

like image 949
Niklas Winde Avatar asked Sep 17 '08 06:09

Niklas Winde


2 Answers

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.

like image 155
jfs Avatar answered Oct 02 '22 20:10

jfs


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.

like image 28
Sam Avatar answered Oct 02 '22 20:10

Sam