【发布时间】:2015-07-27 18:06:39
【问题描述】:
我是 C# 新手,我有一个设备(外围设备),我需要从 C# 控制台应用程序通过串行/USB 进行轮询。虽然下面的代码显然没有抛出任何异常(错误),也没有执行轮询。会发生什么?谢谢。
控制台输出为:
Here goes...
t1: System.Threading.Tasks.Task
PD。从调试中,我的印象是 while(true) {...} 块没有运行。
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);
}
}
}
}
【问题讨论】:
-
while不执行的唯一方法是任务永远不会启动(请参阅stackoverflow.com/questions/12010131/…)。如果不是这种情况,请尝试在您的 while 循环中的answer = ...语句之前放置一个中断,它会被多次击中吗?您的任务可能会在第一次执行时无限期地等待答案。 -
等等...我刚刚意识到你启动了一个异步任务然后程序结束了。尝试等待任务完成。
-
嗨弗拉德,谢谢,但它的行为方式是一样的。
-
尝试在
if (devfound)块的末尾添加t1.Wait() -
感谢您的评论!它正在循环工作......唯一似乎不起作用的是轮询线。
标签: c# multithreading task-parallel-library task polling