我想创建一个任务来运行串行命令。此时我不需要从执行工作的方法返回任何东西。这可能稍后会改变,但我现在很好奇这是怎么回事。
这是我的。我想为任务使用单独的方法而不是创建匿名操作。我试过返回 void,结果是“void cannot be explicitly converted to a Task”。我也试过了。 Task<void>
.我尝试的最后一件事是返回一个任务,但我收到错误“并非所有代码路径都返回一个值”和“无法隐式地将 void 转换为类型任务”
过去我使用线程来完成此操作,但这次我想使用任务。
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;
}
}
最佳答案
只需将doSequence
标记为async
(假设它使用await
):
private async Task doSequence()
此外,最好在传递给 Task.Run
的委托(delegate)中返回此 Task
:
SequenceTask = await Task.Run(() => doSequence());
I would like to create a task to run serial commands on.
这让我相信使用 async
和 Task
可能不是您场景的最佳解决方案。我建议您查看 TPL 数据流。
关于c# - 从类型为 void 的方法返回任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39661424/