Question

je joue avec le tour async ctp ce matin et ont un programme simple avec un button et un label. Cliquez sur le button et il commence à mettre le label, arrêtez le button il cesse d'écrire à la label. Cependant, je ne suis pas sûr de savoir comment réinitialiser le CancellationTokenSource afin que je puisse relancer le processus. Mon code est ci-dessous:

public partial class MainWindow : Window
{
    CancellationTokenSource cts = new CancellationTokenSource();
    public MainWindow()
    {
        InitializeComponent();
        button.Content = "Start";
    }

    async Task DoWork(CancellationToken cancelToken)
    {
        int i = 0;
        while (!cancelToken.IsCancellationRequested)
        {
            label.Content = i++.ToString();
            await TaskEx.Delay(50, cancelToken);
        }
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        if (button.Content == "Start")
        {
            button.Content = "Stop";
            DoWork(cts.Token);
        }
        else
        {
            button.Content = "Start";
            cts.Cancel();
        }
    }
}
Était-ce utile?

La solution

You need to recreate the CancellationTokenSource - there is no way to "reset" this once you set it.

This could be as simple as:

private void Button_Click(object sender, RoutedEventArgs e)
{
    if (button.Content == "Start")
    {
        button.Content = "Stop";
        cts.Dispose(); // Clean up old token source....
        cts = new CancellationTokenSource(); // "Reset" the cancellation token source...
        DoWork(cts.Token);
    }
    else
    {
        button.Content = "Start";
        cts.Cancel();
    }
}

Autres conseils

Even I had same problem and I figured it out that, best way to solve it is to create cancellation token source newly just before calling the method.

this is what I do on my start button click:

cancellationTokenSource = new CancellationTokenSource();
cancellationToken = cancellationTokenSource.Token;
Task.Factory.StartNew(StartUpload, cancellationToken);

I change the caption for the same button to cancel and when a click occurs on cancel, i call

cancellationTokenSource.Cancel();

Here is the full code:

if (button3.Text != "&Start Upload")
        {
            cancellationTokenSource.Cancel();
        }
        else
        {
            try
            {
                cancellationTokenSource = new CancellationTokenSource();
                cancellationToken = cancellationTokenSource.Token;
                Task.Factory.StartNew(StartUpload, cancellationToken);
            }
            catch (AggregateException ex)
            {
                var builder = new StringBuilder();
                foreach (var v in ex.InnerExceptions)
                    builder.Append("\r\n" + v.InnerException);
                MessageBox.Show("There was an exception:\r\n" + builder.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top