【问题标题】:Show elapsed time of a function inside Task.Run C#在 Task.Run C# 中显示函数的经过时间
【发布时间】:2015-01-08 06:37:01
【问题描述】:

我想在文本框中显示使用 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;
        }
    }

【问题讨论】:

    标签: c# multithreading elapsedtime


    【解决方案1】:

    您不是在等待MyFunction 完成,您只是在计算Task.Run 调用的开始时间。等待MyFunction完成,可以等待Task.Run返回的Task。

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

    如果您不熟悉异步编程,请先阅读 herehere

    【讨论】:

    • MyFunction(inputstring, cts.Token) 的示例代码? 参数 CancellationTokenSource.Token ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-15
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多