Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threaded event handling (C#)

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

like image 391
Sebastian Müller Avatar asked Aug 24 '09 09:08

Sebastian Müller


People also ask

Can C be multithreaded?

Can we write multithreading programs in C? Unlike Java, multithreading is not supported by the language standard. POSIX Threads (or Pthreads) is a POSIX standard for threads. Implementation of pthread is available with gcc compiler.

What is event handling in C?

C event handlers allow you to interface more easily to external systems, but allowing you to provide the glue logic. The POS includes a small open source C compiler (TCC) which will dynamically compile and link your C code at runtime. Alternatively, you can precompile and ship a DLL/EXE with your functions.

Is event driven programming single threaded?

Event-driven programming requires less memory than multi-threaded programming because there are no threads that require stack memory. The entire system can run as a single thread, which requires only one single stack.

What is thread-safe in C?

A threadsafe function protects shared resources from concurrent access by locks. Thread safety concerns only the implementation of a function and does not affect its external interface. The use of global data is thread-unsafe.


1 Answers

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
    });
}
like image 61
Fredrik Mörk Avatar answered Oct 04 '22 18:10

Fredrik Mörk