2

我想在文本框中显示使用 Task.Run 调用的函数的执行时间,因为需要一些时间才能完成,我为此创建了一个线程。

问题是当我单击开始按钮时,会立即打印 textBox1 中的时间,我想显示经过的时间,但仅在 MyFunction 完成处理之后或按下取消按钮时。

sw.Stop() 应该去哪里?

我当前的开始和取消按钮代码是:

    void Begin_Click(object sender, EventArgs e)
    {
        Stopwatch sw = Stopwatch.StartNew();

        // Pass the token to the cancelable operation.
        cts = new CancellationTokenSource();

        Task.Run(() => MyFunction(inputstring, cts.Token), cts.Token);

        sw.Stop();

        textBox1.Text += Math.Round(sw.Elapsed.TotalMilliseconds / 1000, 4) + " sec";
    }

    void Cancel_Click(object sender, EventArgs e)
    {
        if (cts != null)
        {
            cts.Cancel();
            cts = null;
        }
    }
4

1 回答 1

4

您无需等待MyFunction完成,您只是在计算Task.Run通话的开始时间。要等待MyFunction完成,您可以等待返回的任务Task.Run

async void Begin_Click(object sender, EventArgs e)//<--Note the async keyword here
{
    Stopwatch sw = Stopwatch.StartNew();

    // Pass the token to the cancelable operation.
    cts = new CancellationTokenSource();

    await Task.Run(() => MyFunction(inputstring, cts.Token), cts.Token);//<--Note the await keyword here

    sw.Stop();

    textBox1.Text += Math.Round(sw.Elapsed.TotalMilliseconds / 1000, 4) + " sec";
}

如果您不熟悉异步编程,请从阅读此处此处开始

于 2015-01-08T06:39:05.477 回答