而操作正在运行Assynchronous对消 [英] Assynchronous Cancelation while operation is running

查看:105
本文介绍了而操作正在运行Assynchronous对消的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始约在.NET异步编程了一些测试,现在我停留在尝试使用TI的CancellationToken取消长时间操作。

I'm starting a few tests about asynchronous programing in .net and now i'm stuck at trying ti cancel a long operation using cancellationToken.

所以,我有以下的code:

So I have the following code:

CancellationTokenSource cancelationToken = new CancellationTokenSource();

我的按钮启动操作

My buttons to start the operations

    private void button2_Click(object sender, EventArgs e)
    {
        cancelationToken.Cancel(true);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        StartOperation(cancelationToken.Token);
    }

最后我操作

    private async void StartOperation(CancellationToken cancelToken)
    {
        await GetItensFromDatabase2(cancelToken);
    }

    public static Task<int> GetItensFromDatabase(CancellationToken cancelToken)
    {
        //cancelToken.Register( () => Console.WriteLine("Canceled") );
        return Task.Factory.StartNew<int>(() =>
        {
            int result = 0;

            cancelToken.ThrowIfCancellationRequested();

            result = MyLongOperation();  // Simulates my operation -> I want to cancel while this operation is still running

            return result;

        }, cancelToken);
    }

那么,如何取消MyLongOperation()方法?是否有可能呢?

So, how to cancel MyLongOperation() method ? Is it possible to do ?

推荐答案

有不可能取消在任何点,的CancellationToken的目的是允许用户取消操作中,当长时间运行操作期望...

It is not possible to cancel in any point, the purpose of CancellationToken is to allow user to cancel the operation, when the long running operation expect that...

while(!finished)
{
     cancelToken.ThrowIfCancellationRequested();
     //Some not cancelable operations
}

下面是取消的方法比较常见的方法

Here is more common method of cancelable method

private static void LongRunning(CancellationToken cancelToken)
{
    while (true)
    {
        if(cancelToken.IsCancellationRequested)
        {
            return;
        }
        //Not canceled, continue to work
    }
}

我们的想法是,用户请求取消,而只是执行者决定何时停止他的工作。达到了一些安全点后,一般做执行人取消

The idea is, that user requests cancellation, but only executor decides when to stop his work. Usually executor do cancellation after reaching some "safe-point"

这是不好的experiance到中止长期运行的操作,而不会问oppinion,很多帖子都被写了关于这一点。

It is not good experiance to Abort long running operations without asking oppinion, a lot of posts have been written about this.

这篇关于而操作正在运行Assynchronous对消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆