我想创建一个运行串行命令的任务。目前,我不需要从执行工作的方法中返回任何内容。这可能会在以后改变,但现在我很好奇如何实现这一点。
这是我的代码。我想使用一个单独的方法来处理任务,而不是创建一个匿名操作。我尝试了返回void,结果是“void不能明确转换为Task”。我还尝试了
这是我的代码。我想使用一个单独的方法来处理任务,而不是创建一个匿名操作。我尝试了返回void,结果是“void不能明确转换为Task”。我还尝试了
Task<void>
。最后我尝试了返回一个Task,但我收到了错误消息“Not all Code paths return a value”和“Can not implicily convert void to type task”。
过去我用线程来实现,但这次我想使用任务。
internal class Hardware
{
private EventHandler<SequenceDoneEventArgs> SequenceDone;
private List<Step> Steps;
private System.IO.Ports.SerialPort comport = null;
private Task SequenceTask;
private CancellationTokenSource RequestStopSource;
private CancellationToken RequestStopToken;
private void Initialize()
{
comport = new System.IO.Ports.SerialPort("COM2", 115200, System.IO.Ports.Parity.None,8);
comport.DataReceived += Comport_DataReceived;
}
public async void RunSequence()
{
if (comport == null)
{
Initialize();
}
if (!comport.IsOpen)
{
comport.Open();
}
RequestStopSource = new CancellationTokenSource();
RequestStopToken = RequestStopSource.Token;
SequenceTask = await Task.Run(() => { doSequence(); });
}
private Task doSequence()
{
//** Run Sequence stuff here
}
}
预计时间:
最终这是我的完整解决方案
internal class Hardware
{
private EventHandler<SequenceDoneEventArgs> SequenceDone;
private List<Step> Steps;
private System.IO.Ports.SerialPort comport = null;
private Task SequenceTask;
private CancellationTokenSource RequestStopSource;
private CancellationToken RequestStopToken;
private void Initialize()
{
comport = new System.IO.Ports.SerialPort("COM2", 115200, System.IO.Ports.Parity.None,8);
comport.DataReceived += Comport_DataReceived;
}
public async void RunSequence()
{
if (comport == null)
{
Initialize();
}
if (!comport.IsOpen)
{
comport.Open();
}
RequestStopSource = new CancellationTokenSource();
RequestStopToken = RequestStopSource.Token;
SequenceTask = await Task.Factory.StartNew(async () => { await doSequence(); });
}
private Task doSequence()
{
//** Run Sequence stuff here
//return null;
return Task.CompletedTask;
}
}
Task
? - defaultTask
是不正确的吗? - defaultTask.FromResult()
吗? - default