Question

I have a winforms app with a long running task and two buttons. One button Start and one Stop.

A new task with a cancellation Token starts when I press the start button. And if I press the Stop button the cancellation Token's Cancel Method gets called.

I want the UI to be usable during all the time so where do I put the try, catch block for this job. In all the examples I saw they put it around t.Wait();

But if I do that the UI freezes and that is the reason why I used a Task in the first place, to continue using the ui while doing the task. So where to put the try catch block without using Task.Wait.

Start button:

 tokenSource2 = new CancellationTokenSource();
   ct = tokenSource2.Token;
   t = new Task(doStart, ct);
   t.Start();

Stop button:

tokenSource2.Cancel();
Was it helpful?

Solution

You could update doStart to handle the cancellation event and exit the task gracefully so you wouldn't need to use Wait at all e.g.

public void doStart(CancellationToken token)
{
    while(...)
    {
        ...
        if (token.IsCancellationRequested)
            break;
    }
}

Alternatively, you could wait for the task result on another thread e.g.

Thread.QueueUserWorkItem((state) =>
{
    try
    {
        t.Wait();
    }
    catch(...)
    {
        ...
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top