5

I have a question about event handling with C#. I listen to events a class A throws. Now when the event ist thrown a method is executed that does something. This method sometimes has to wait for respones from datasources or similar.

I think event handling is synchronous so one after another event will be processed. Is it possible to makes this asynchronous? I mean that when the method is executed but has to wait for the response of the datasource another event can be processed?

Thanks in advance

Sebastian

Sebastian Müller
  • 5,471
  • 13
  • 51
  • 79

2 Answers2

11

I assume that you can spawn the code that needs to wait in a new thread. This would cause the event handler to not block the thread on which the events are being raised, so that it can invoke the next event handler in line. (C# 3.5 sample)

private void MyPotentiallyLongRunningEventHandler(object sender, SomeEventArgs e)
{
    ThreadPool.QueueUserWorkItem((state) => {
        // do something that potentially takes time

        // do something to update state somewhere with the new data
    });
}
Fredrik Mörk
  • 155,851
  • 29
  • 291
  • 343
  • What if the arguments (SomeEventArgs) contain any output parameters? The method cannot leave until the output parameters are computed... I've posted a related question here: http://stackoverflow.com/questions/6453655/parallel-event-handling-in-c/6453701#6453701 – Kill KRT Jun 27 '11 at 11:08
2

Simple, create a thread in your event handler and do all the logic there. It's better to use thread pool so number of threads is bounded.

vava
  • 24,851
  • 11
  • 64
  • 79
  • Creating a thread is not cheap, so that will probably not be a good idea for an event handler, but you could use the thread pool as you say. – Brian Rasmussen Aug 24 '09 at 09:50
  • I don't think thread pool always have pre-created threads around, I think it will create them first few times so you'll pay that cost anyway. – vava Aug 24 '09 at 14:02