user3324178
user3324178

Reputation: 33

Running a separate thread, updating the UI and being able to cancel it

I have a Windows Forms application that runs a process that takes up to 3 hours to complete. While it is running I would like the UI to be responsive to 'Stop' commands and also to update on the progress of the job. In simple terms the long running task is going around a loop thousands of times processing records and it's within this loop that I would like to update the UI.

I have managed to get code running using the FromCurrentSynchronizationContext option with TPL Tasks. I have also used CancellationTokens to cancel a running thread.

However I cannot work out how to combine the two.

Upvotes: 0

Views: 229

Answers (1)

James
James

Reputation: 82136

Not sure what you mean by "combine the two" but here is a very simple example of a long running task with cancellation support which updates a UI component after each iteration

var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;

Task.Run(() => 
{
    for(int i = 0; i <= 50; i++)
    {
        Thread.Sleep(300); // simulate work
        // check if the task has been cancelled and throw if required
        if (token.IsCancellationRequested)
            token.ThrowIfCancellationRequested();
        // otherwise update the UI
        someTextBox.Invoke(() => someTextBox.Text = String.Format("Iteration: {0}", i));
    }
}
, token);
// cancel the task after 5 seconds
Task.Run(async delegate 
{
    await Task.Delay(5000); 
    tokenSource.Cancel(); 
});

Upvotes: 2

Related Questions