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