如何解决两个任务之间的X秒延迟C#
我想在任务1和任务2之间延迟80毫秒。 但是这里任务1和任务2一起运行。 我的代码:
private CancellationTokenSource cts = new CancellationTokenSource();
private async void button4_Click(object sender,EventArgs e)
{
//SendBuyOrder();
try
{
await Task.WhenAll(Task1(cts.Token),Task2(cts.Token));
//await Task.WhenAll(Task1(cts.Token));
}
catch (Exception ex)
{
}
}
public void send(int t)
{
txtResult.AppendText("Task" + t + ": " + DateTime.Now.ToString("hh:mm:ss.fff"));
txtResult.AppendText(Environment.NewLine);
txtResult.AppendText(Environment.NewLine);
}
public async Task Task1(CancellationToken token)
{
while (true)
{
token.ThrowIfCancellationRequested();
await Task.Delay(Convert.ToInt32(txtRepeatInterval.Text),token);
send(1);
}
}
public async Task Task2(CancellationToken token)
{
while (true)
{
token.ThrowIfCancellationRequested();
await Task.Delay(Convert.ToInt32(txtRepeatInterval.Text),token);
send(2);
}
}
此处,任务1和任务2一起运行,并且在任务1重新运行后80毫秒。我希望任务2在开始任务1后80毫秒内执行
解决方法
您可以执行一项同时执行两项任务的任务:
public async Task Task3(CancellationToken token)
{
while (true)
{
token.ThrowIfCancellationRequested();
await Task.Delay(Convert.ToInt32(txtRepeatInterval.Text),token);
send(1);
await Task.Delay(80,token);
send(2);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。