Reputation: 311
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);
}
}
}
}
Upvotes: 2
Views: 765
Reputation: 30464
Whenever you do async programming, and you start a separate task to perform actions while you do other things, then there ought be some place in time where you wait for results from the other task.
Officially you don't know when the other task will start, unless you start fiddling with priorities and stuff. It's up to the operating system to decide after which of your statements the other task starts. So after some processing of yourself you are never certain whether the other task is already started and what it has done, unless you start waiting for some sign of life of the other task.
You can check for the status of the other task, but then you only know whether it started running, maybe it only has performed the first statement. You'll never certain when it will do the next statements.
Proper ways to know about the status of the other task: - Wait for it to finish. Useful if you only need the result - Wait for some semaphores / events / etc. to be signalled. Useful if you need to be kept informed about the others task progress
Upvotes: 0
Reputation: 1919
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();
}
}
Upvotes: 2