【问题标题】:C# how to stop a async task on button clickC#如何在按钮单击时停止异步任务
【发布时间】:2019-11-19 12:33:31
【问题描述】:

我刚刚在 C# 中发现了 async 关键字,只是想知道如何使用按钮单击来停止它。我只想了解它是如何工作的,以及在执行另一个事件后如何停止任务。我尝试使用 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);
}

【问题讨论】:

标签: c# task


【解决方案1】:

你可以试试这样的

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();
}

【讨论】:

  • 上面写着The 'await' operator can only be used within an async lambda expression.
  • 抱歉,已更新!可能您需要找到另一种方法来模拟延迟
【解决方案2】:

我想如果你想在某些情况下停止线程 你可以做这些

 private void button1_Click(object sender, EventArgs e)
{
    var tokenSource2 = new CancellationTokenSource();
    CancellationToken ct = tokenSource2.Token;

    Read(ct);
}



private async void Read( CancellationToken cancellationToken)
{
    if (cancellationToken.IsCancellationRequested)
    {
           Thread.Sleep(4000);
    }
}

【讨论】:

  • 那怎么取消呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多