I want to delay 80 milliseconds between task 1 and task 2. But here Task 1 and Task 2 run together. my code:
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);
}
}
Here, Task 1 and Task 2 are run together, and 80 milliseconds after Task 1 is run again. I want task 2 to be performed 80 milliseconds after starting task 1
You can make one task that does both:
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.