我是 C# 新手,我有一个设备(外设),需要从 C# 控制台应用程序通过串行/USB 进行轮询。尽管下面的代码显然没有抛出任何异常(错误),也没有执行轮询。可能发生什么情况?谢谢。
控制台输出为:
Here goes...
t1: System.Threading.Tasks.Task
PD。通过调试,我的印象是 while(true) {...} block 没有运行。
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);
}
}
}
}
最佳答案
在您的示例中,您启动了一个新的异步任务,同时您的应用程序继续执行到 Main
方法的末尾,并在新任务有机会执行之前突然退出执行其内容(在您的例子中,是 while 循环
)。
您需要等待任务完成(或者在您的情况下,执行直到杀死它)。尝试像这样构建您的代码:
static void Main(string[] args)
{
//// Your initialization code
if (devfound)
{
//// Device found, prepare for task
var t1 = Task.Factory.StartNew(() =>
{
//// Task body
});
t1.Wait();
}
}
关于c# - 使用任务并行库(TPL)进行轮询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31660197/