views:

167

answers:

2

Hi community,

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

+8  A: 

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
+2  A: 

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
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
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