首页

源码搜藏网

首页 > 开发教程 > .net教程 >

使用Cinchoo框架异步中止的长时间运行的任务

创建时间:2016-06-01 09:48  

介绍
在.NET中,有许多的方法,使您可以通过使用线程/任务/线程池启动异步长时间运行的任务。每一个方法都有利弊吧。请参考MSDN有关它们的详细信息。随着TPL,你接触到取消模式,让你可以优雅地阻止你的长期运行的任务。在这篇文章中,我将阐述有关的方式开始中止的长期运行的任务异步使用Cinchoo框架和谈论中止它在一个强有力的方式的方式。
 
首先,每个Windows应用程序,使用它来呈现窗口/执行的主要任务,处理事件,并执行自定义代码的单一主线程。在单线程环境中,任何长时间运行的任务将阻止主线程。特别是,它会阻塞主UI线程和应用程序在Windows应用程序变得反应迟钝。
 
Cinchoo简化模型异步执行长时间运行的任务,并将控制权交给调用者随时终止它。除了标准的行为,它提供了故障,通过API超时时间的情况下,一些有用的功能,如重试次数。好吧,让我们切入正题上如何使用代码来使用它们。
 
下面是功能的总结:
 
通过随时中止任务中止()方法
可以指定超时周期运行任务
在任务失败的情况下自动重试
做出决定继续通过回调机理重试
下载最新Cinchoo 二进制这里。(的NuGet命令:安装封装Cinchoo)
 
使用代码
该API是通过暴露ChoActionEx 类。API的签名看起来象下面这样:
 
public static class ChoActionEx
{
    public static ChoAbortableAsyncResult RunAsync
(this Action action, ChoAbortableAsyncCallback callback = null, object state = null, 
int timeout = -1, int maxNoOfRetry = 0, int sleepBetweenRetry = 5000);
}
哪里:
 
行动 -一个长时间运行的任务的方法
回调 -引用的方法的相应的异步操作完成时被调用
状态 -有资格或包含关于异步操作的信息的用户定义的对象
超时 -以毫秒为单位的超时值。-1,无限
maxNoOfRetry -失败的情况下所作的重试次数的最大值
sleepBetweenRetry -毫秒数重试之间的休眠。默认值是5000毫秒
这个API方法返回ChoAbortableAsyncResult对象。这种封装异步操作的委托结果。它暴露了以下成员:
 
AsyncState -获取在'提供的对象状态一的“参数RunAsync 方法调用
AsyncWaitHandle -获取的WaitHandle,封装的Win32同步句柄,并允许各种同步计划的实施
CompletedSynchronously -获取指示是否值RunAsync调用同步完成
IsAborted -获取指示服务器是否已经中止呼叫的价值
IsCompleted -获取一个值,指示服务器是否已完成呼叫
IsRetryAttempt -获取一个值,指示服务器是否已重试通话
IsTimeout -获取指示方法是否已与超时完成值
结果 -从获取的结果值异步如有来电
RetryCount重 -获取重试尝试的数目由服务器取得的值
例外 -获取任务执行期间捕获任何异常
CanContinue -获取或设置继续重试
EndInvoke会() -获取异步操作的返回值。如果异步操作尚未完成,该函数将阻塞,直到该结果可用
中止() -中止当前正在执行的-异步调用
#1试样
 
下面的示例显示了如何asynchrounously执行一个方法,等待它完成。
 
隐藏   复制代码
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Main thread: {0}", Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine();
 
        //Run method async, wait for it to complete
        Console.WriteLine("TEST #1: Run method, wait for it to complete...");
        ChoAbortableAsyncResult r = ChoActionEx.RunAsync(LongRunningTask);
        Console.WriteLine("Waiting for worker thread to complete.");
        r.EndInvoke();
        Console.WriteLine();
    }
 
    private static void LongRunningTask()
    {
        Console.WriteLine("Starting task... (Sleeping for 10 secs)");
        Console.WriteLine("Worker thread: {0}", Thread.CurrentThread.ManagedThreadId);
        Thread.Sleep(10 * 1000);
        Console.WriteLine("Task completed.");
    }
}
样品#2
 
下面的示例显示了如何asynchrounously执行一个方法,中止后5秒吧。
 
隐藏   复制代码
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Main thread: {0}", Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine();
 
        //Run method async, abort it after 5 secs
        Console.WriteLine("TEST #2: Run method, abort after 5 secs...");
        ChoAbortableAsyncResult r1 = ChoActionEx.RunAsync(LongRunningTask);
        Console.WriteLine("Waiting for 5 secs...");
        Thread.Sleep(5000);
        Console.WriteLine("Aborting working thread.");
        r1.Abort();
        Console.WriteLine();
    }
 
    private static void LongRunningTask()
    {
        Console.WriteLine("Starting task... (Sleeping for 10 secs)");
        Console.WriteLine("Worker thread: {0}", Thread.CurrentThread.ManagedThreadId);
        Thread.Sleep(10 * 1000);
        Console.WriteLine("Task completed.");
    }
}
样品#3
 
下面的示例显示了如何asynchrounously执行一个方法,超时后5秒。
 
隐藏   缩小    复制代码
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Main thread: {0}", Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine();
 
        //Run method async, with timeout 5 secs
        Console.WriteLine("TEST #3: Run method with 5 secs timeout...");
        ChoAbortableAsyncResult r2 = ChoActionEx.RunAsync(LongRunningTask, null, null, 5000);
        Console.WriteLine("Waiting for worker thread to complete or timeout.");
        try
        {
            r2.EndInvoke();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        Console.WriteLine();
    }
 
    private static void LongRunningTask()
    {
        Console.WriteLine("Starting task... (Sleeping for 10 secs)");
        Console.WriteLine("Worker thread: {0}", Thread.CurrentThread.ManagedThreadId);
        Thread.Sleep(10 * 1000);
        Console.WriteLine("Task completed.");
    }
}
样品#4
 
下面的示例显示了如何asynchrounously执行一个方法,重试几次尝试。
 
隐藏   缩小    复制代码
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Main thread: {0}", Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine();
 
        //Run a exception thrown method async 
        Console.WriteLine("TEST #4: Run method with 2 retries...");
        ChoAbortableAsyncResult r3 = 
ChoActionEx.RunAsync(LongRunningTaskWithException, null, null, -1, 2, 5000);
        Console.WriteLine("Waiting for worker thread to complete.");
        try
        {
            r3.EndInvoke();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        Console.WriteLine();
    }
    
    private static void LongRunningTaskWithException()
    {
        Console.WriteLine("Starting task... (Sleeping for 10 secs)");
        Console.WriteLine("Worker thread: {0}", Thread.CurrentThread.ManagedThreadId);
        Thread.Sleep(10 * 1000);
        throw new ApplicationException("Test task exception.");
    }
}
样品#5
 
下面的示例显示了如何asynchrounously执行的方法,取消在回调了。
 
隐藏   缩小    复制代码
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Main thread: {0}", Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine();
 
        Console.WriteLine("TEST #5: Run method with 2 retries, but cancel the retry on callback...");
        ChoAbortableAsyncResult r5 = ChoActionEx.RunAsync(LongRunningTaskWithException, (t) =>
        {
            ChoAbortableAsyncResult t1 = t as ChoAbortableAsyncResult;
            Console.WriteLine("Canceling the task...");
            if (t1.Exception != null)
                t1.CanContinue = false;
        }, null, -1, 2, 5000);
        try
        {
            r5.EndInvoke();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        Console.WriteLine();
    }
    
    private static void LongRunningTaskWithException()
    {
        Console.WriteLine("Starting task... (Sleeping for 10 secs)");
        Console.WriteLine("Worker thread: {0}", Thread.CurrentThread.ManagedThreadId);
        Thread.Sleep(10 * 1000);
        throw new ApplicationException("Test task exception.");
    }
}
 
上一篇:拍摄照片到新的水平 - 第三部分:图像切换按钮
下一篇:没有了

相关内容

热门推荐