Stopping a task without a CancellationToken

后端 未结 3 1572
我寻月下人不归
我寻月下人不归 2020-12-19 04:22

I am using an external library that has async methods, but not CancellationToken overloads.

Now currently I am using an extension method fr

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-19 04:45

    As you suggest you can cancel a task by passing in a CancellationToken and then calling Cancel.

    As for how you'd go about triggering that cancellation depends on the nature of your application.

    A few possible scenarios

    1. Carry on until you click cancel
    2. Cancel after a fixed time
    3. Cancel if there's been no progress for a fixed time

    In case 1 you simply cancel the task from your cancel button, for example

    private void cancel_Click(object sender, RoutedEventArgs e)
    {
        ...
        cts = new CancellationTokenSource();
        await MyAsyncTask(cts.Token);
        cts.Cancel();
        ...
    }
    

    In case 2 you could start a timer when you start your task and then cancel the task after a set time using CancelAfter, for example

    private void start_Click(object sender, RoutedEventArgs e)
    {
        ...
        cts = new CancellationTokenSource();
        cts.CancelAfter(30000);
        await MyAsyncTask(cts.Token);
        ...
    }
    

    In case 3 you could do something with progress, for example

    private void start_Click(object sender, RoutedEventArgs e)
    {
        ...
        Progress progressIndicator = new Progress(ReportProgress);
        cts = new CancellationTokenSource();
        await MyAsyncTask(progressIndicator, cts.Token);
        ...
    }
    
    void ReportProgress(int value)
    {
        // Cancel if no progress
    }
    

    Here are a few useful links Parallel programming, task cancellation, progress and cancellation, cancel tasks after set time, and cancel a list of tasks.

提交回复
热议问题