.Net Thread vs ThreadPool vs Task for SerialPort Communication

I had an interesting problem in my C # .Net 4.0 application using class SerialPortand ThreadPool.QueueUserWorkItemor or Tasks.

The problem only occurs when 2 or more serial ports are used simultaneously. Each serial port runs in its own thread, which I create in one of three ways:

  • new Thread(DoSerialCommX)
  • ThreadPool.QueueUserWorkItem(DoSerialCommX)
  • new Task(DoSerialCommX, TaskCreationOptions.LongRunning).Start()

To illustrate the problem, I created a method DoSerialCommXfor reading and writing to the serial port forever in a loop. It looks something like this: (I actually do not do this in my real program. This is just a fragment of my test program that isolates and illustrates the problem).

private void DoSerialCommX()
{
    SerialPort port = new SerialPort("ComX", 9600);
    port.Open();

    while(true)
    {
        //Read and write to serial port
    }
}

2 3, , - . 1, . , , , , Intel Atom. , , .

, , Task . , . TaskCreationOptions.LongRunning, , , , , .

, : Thread ? - Thread, -?

Edit: , , , ThreadPool Tasks . . , . , Thread , ThreadPool Task - . , ?

+5
4

1, 2 3 , . , - , . , .

, :

  • (, ..) threadpool # 2 # 3, .
  • Atom. Atom , . = , (-) .

2 3 - - . , , - IO, , .. (, ?)

2 3, Async IO. - , , , Threadpool.

+2

, , / COM-. , ( ) .

, / , , .

+1

- , , " ", . , (mod. threadpool ).

9600 , , , .

+1

, :

  • Thread , Thread.Start() , .
  • ThreadPool , ThreadPool. ThreadPool , ( ) .
  • , . , .

So, if you want your task to start quickly, always use Thread. Both tasks and ThreadPool have some additional “infrastructure overhead” that may cause slight delays that you notice.

Since both ThreadPool and the task are not intended to be used when your task never exists, I suggest you use Thread.

0
source

All Articles