C#如何在按钮单击时停止异步任务

Sar*_*obi 0 c# task

我刚刚async在 C# 中发现了关键字,只是想知道如何使用按钮单击来停止它。我只是想了解它是如何工作的以及如何在执行另一个事件后停止任务。我尝试使用 bool 停止它,但没有运气。吹是我的代码:

//start
private void button1_Click(object sender, EventArgs e)
{
    Read(true);
}

private async void Read(bool state)
{
    while (state == true)
    {
        await Task.Delay(4000);
        listBox1.Items.Insert(0, "Read 1");
    }
}

//stop
private void button2_Click(object sender, EventArgs e)
{
    Read(false);
}
Run Code Online (Sandbox Code Playgroud)

Die*_*ans 5

你可以试试这样的

private CancellationTokenSource cancellationToken;

//start
private void button1_Click(object sender, EventArgs e)
{
    cancellationToken= new CancellationTokenSource();
    Read();
}



private async void Read()
{
    Task.Factory.StartNew(() =>
    {
       listBox1.Items.Insert(0, "Read 1");
    }, cancellationToken.Token);
}


//stop
private void button2_Click(object sender, EventArgs e)
{
    if(cancellationToken!= null) 
    cancellationToken.Cancel();
}
Run Code Online (Sandbox Code Playgroud)