Search code examples
c#multithreadingtask-parallel-librarytaskpolling

Using task parallel library (TPL) for polling


I am new in C# and I have a device (peripheral) which I need to poll through serial/USB from a C# console application. Though the code below apparently does not throw any exceptions (errors), nor it executes the polling. What could be happening ? Thanks.

The console output is:

Here goes...
t1: System.Threading.Tasks.Task

PD. From debugging, I have the impression the while(true) {...} block is not ran.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using T1NET;

namespace ValController
{
    class Program
    {
        static void Main(string[] args)
        {

            T1NET.comm Device = new T1NET.comm();
            bool devfound = true;
            Device.Port = new T1NET.COM_port();
            Device.Port.RtsEnable = false;
            Device.HandlePort = true;
            Device.Port.BaudRate = 9600;
            Device.Port.PortName = "COM4";
            Device.Device = T1NET.Device.Valid;
            Device.Port.ReadTimeout = 100;

            if (devfound)
            {
                BV_Device.HandlePort = true;
                Console.WriteLine("here goes...");
                var t1 = Task.Factory.StartNew(() =>
                {
                    while (true)
                    {
                        System.Threading.Thread.Sleep(100);
                        System.Threading.Thread.BeginCriticalRegion();
                        T1NET.Answer answer = Device.RunCommand(T1NET.T1NETCommand.Poll);
                        Console.WriteLine("answer:" + answer);
                    }
                });

                Console.WriteLine("t1: " + t1);

            }
        }
    }
}

Solution

  • In your sample, you started a new asynchronous task, while at the same time your application continues its execution to the end of the Main method and suddenly exits before your new task even has a chance of executing its content (in your case, the while loop).

    You need to wait for your task to complete (or in your case, execute until you kill it). Try structuring your code like this:

    static void Main(string[] args)
    {
        //// Your initialization code
    
       if (devfound)
       {
            //// Device found, prepare for task
            var t1 = Task.Factory.StartNew(() =>
            {
                //// Task body
            });
    
            t1.Wait();
       }
    }