Reputation: 95
I want to show in textbox the time execution of a function that is called using Task.Run, since takes some time to complete and I'd created a thread for that.
The issue is when I click on begin button is printed inmediately the time in textBox1 and I want to show the Elapsed time but only just after MyFunction completes the processing or when Cancel button is pressed.
Where should go sw.Stop()?
My current code for Begin and cancel button is:
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;
}
}
Upvotes: 2
Views: 5454
Reputation: 73472
You're not waiting for the MyFunction
to complete, You're simply calculating the start time of the Task.Run
call. To wait for the MyFunction
to complete, you can await the Task returned by 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";
}
If you're new to asynchronous programming start by reading here and here
Upvotes: 4