我想在文本框中显示使用 Task.Run 调用的函数的执行时间,因为需要一些时间 完成,我为此创建了一个线程。
问题是当我点击开始按钮时,文本框 1 中的时间会立即打印出来,我想显示 耗时,但仅在 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;
}
}
请您参考如下方法:
您不是在等待 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";
}
