在C#中取消任务方法

时间:2015-09-28 10:24:35

标签: c# async-await

我的View Model

中有这样的异步方法
public async Task Download()
{
//Do some background thread to do heavywork and recursive task
await Download();
}

然后我称之为我的观点

private async Task LoadData()
{
_vm.Download();
//Do other background task
await _vm.DoElse();
}

并像这样称呼它

Task.Factory.StartNew(async()=> {await LoadData();});

现在我的问题是如何取消Download()

1 个答案:

答案 0 :(得分:0)

您应该传递给异步方法CancellationToken

然后你应该在每次迭代时检查它:

public async Task Download(CancellationToken cancellationToken)
{
    if (cancellationToken.IsCancellationRequested)
    {
        //Do work on cancel
        return;
    }
    //Do some background thread to do heavywork and recursive task
    await Download();
}

要在外面取消它,您应该处理CancellationTokenSource对象之外的某个位置,当您想要取消时,只需致电_cancellationTokenSource.Cancel()

Task.Factory.StartNew(async()=> {await LoadData(_cancellationTokenSource.Token);});

private async Task LoadData(CancellationToken cancellationToken)
{
    await _vm.Download(cancellationToken);
    //Do other background task
    await _vm.DoElse(cancellationToken);
}