0

I need to perform two parallel tasks multiple times in a .NET 3.5/C#/WPF program.

In my case, the tasks perform some calculation on data provided by a device (Kinect). So each time new data are received I need to start two tasks doing different computation. I am using Thread for each task and when I receive new data I recreate each thread with a new statement.

// Data received
task1 = new Thread(new ThreadStart(ExtractData1));
task2 = new Thread(new ThreadStart(ExtractData2));

Everything is working correctly, but my question is about efficiency. I am wondering if there is a better way to accomplish this...

Should I keep using Thread like this ? Is there a performance hit to recreate the Thread each time ? Should I create the Thread only once and use ManualResetEvent to trigger the computation ?

Thanks in advance.

Nems
  • 3
  • 1
  • There is a version of Microsofts Reactive Extensions, which claim to 'bridge' some functions of the 4.0 TPL. Maybe it's interesting for you: http://www.microsoft.com/en-us/download/confirmation.aspx?id=24940 – Andreas H. Nov 17 '13 at 00:10
  • Thanks for your advice. I am thinking to switch to .NET 4/4.5 now... – Nems Nov 17 '13 at 00:47

2 Answers2

0

The creation of each thread causes about 1MB of memory to be allocated for its stack. That's expensive.

Unless your calculation is processor intensive then don't bother with threads.

Your best bet is to benchmark all three of the options.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
0

Starting a new Thread does carry some additional overhead, one possible alternative is to make use of the ThreadPool.

ThreadPool.QueueUserWorkItem(new WaitCallback(o => ExtractData1()));
ThreadPool.QueueUserWorkItem(new WaitCallback(o => ExtractData2()));

Here is a comparison of starting a new Thread vs using the ThreadPool. The real summary is that a thread is usually more performant for longer running tasks (something which may take more than a second or two) whereas the ThreadPool is able to recycle existing threads, which alleviates a lot of the initial overhead.

Community
  • 1
  • 1
Lukazoid
  • 19,016
  • 3
  • 62
  • 85
  • On .NET 4.0+ check the [Task](http://msdn.microsoft.com/en-us/library/dd537609.aspx) class. It uses `ThreadPool` to manage work behind the scenes and provides an easier to use API. – Wagner DosAnjos Nov 17 '13 at 00:07
  • The asker is using .NET 3.5 which is pre-TPL, but yes, the TPL does alleviate a lot of these problems if it is available. – Lukazoid Nov 17 '13 at 00:08
  • Thanks, I will go with `ThreadPool`... I can also switch to .NET 4 or 4.5, in that case should I use `Task` ? (Should I edit my question to add a .NET 4/4.5 part ?) – Nems Nov 17 '13 at 00:43
  • @Nems I'm glad the answer helped, be sure to mark as answer once you are able :) – Lukazoid Nov 17 '13 at 00:44
  • @Nems - If you are switching to .Net 4.0 or higher, `TPL` is a way to go for sure. – Rohit Vats Nov 17 '13 at 08:27