【问题标题】:X second delay between two tasks c#两个任务之间的 X 秒延迟 c#
【发布时间】: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

enter image description here

【问题讨论】:

  • 附带说明,Task1Task2 通常不适合用于方法,尤其是异步方法。方法名应该是verbs or verb phrases,异步方法应该有Async suffix

标签: c# multithreading asynchronous parallel-processing async-await


【解决方案1】:

你可以做一个同时完成这两个任务的任务:

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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    相关资源
    最近更新 更多