Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Multithreading

lets say i have an event which gets fired like 10 times per secod

void Session_OnEvent(object sender, CustomEventArgs e)
{
  //DoStuff

  DoLongOperation(e);
}

i want the method DoLongOperation(e); to be processed on a seperated thread everytime the event gets fired,

i could do something like :

new Thread(DoLongOperation).Start(e);

but i have a feeling this is not good for performance, i wanna achieve the best performance, so what the the best thing i can do ?

thanks idvance..

edit:when i said long i didnt mean an opration that would take more than 1 sec maximum its just i dont want the event to wait that time so i wanna make that in seperated thread...

like image 219
Stacker Avatar asked Dec 22 '22 20:12

Stacker


1 Answers

The direct answer to your question is: use the managed thread pool by utilizing ThreadPool.QueueUserWorkItem to push your operations to it. (You may want to take a look at the answer to the question "when do I use the thread pool vs. my own threads?").

However, look at the bigger picture: if all the operations you are starting take more than 100 msec to finish, then you are mathematically going to generate more work than you can handle. This is not going to end well no matter how you slice it. For example, if you create a separate thread each time then your process will run out of threads, if you use the thread pool then you will swamp it with work that it will never be able to finish, etc.

If only some of your operations end up being long, and most complete immediately, then you may have a chance for a practical solution. Otherwise, you need to rethink your program design.

like image 89
Jon Avatar answered Jan 08 '23 14:01

Jon