我试图停止任务一秒钟。我想让循环休息1秒。当我使用await Task.Delay()
时,“主要”任务不会等待它。即使使用Wait()
方法,我也尝试过。我有想法使用ContinueWith()
或IsCompleted
,但这似乎不是最佳解决方案。
有我的代码:
public override void StartSending(Action<BinaryWriter, byte[]> writerAction)
{
_stopSending = false;
try
{
Task.Factory.StartNew(async () =>
{
await using var streamWriter = new BinaryWriter(_stream);
while (!_stopSending)
{
await Task.Delay(1000);
if (PacketsToSend.IsEmpty)
{
writerAction(streamWriter, new byte[] { });
}
else
{
PacketsToSend.TryDequeue(out var toSend);
writerAction(streamWriter, toSend);
}
}
}, TaskCreationOptions.LongRunning);
}
catch (Exception e)
{
OnErrorOccured(e);
}
}