【发布时间】:2020-12-12 03:32:34
【问题描述】:
我想在任务 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);
}
}
这里,Task 1 和 Task 2 一起运行,并且在 Task 1 再次运行 80 毫秒后。我希望在启动任务 1 后 80 毫秒执行任务 2
【问题讨论】:
-
附带说明,
Task1和Task2通常不适合用于方法,尤其是异步方法。方法名应该是verbs or verb phrases,异步方法应该有Async suffix。
标签: c# multithreading asynchronous parallel-processing async-await