简单实现C#异步操作

在.net4.0以后异步操作,并行计算变得异常简单,但是由于公司项目开发基于.net3.5所以无法用到4.0的并行计算以及Task等异步编程。因此,为了以后更方便的进行异步方式的开发,我封装实现了异步编程框架,通过BeginInvoke、EndInvoke的方式实现异步编程。

一、框架结构

整个框架包括四个部分

1、基类抽象Opeartor
我把每个异步执行过程称为一个Operate,因此需要一个Opeartor去执行
2、FuncAsync
异步的Func
3、ActionAsync
异步的Action
4、Asynchorus
对ActionAsync和FuncAsync的封装

Operator
Operator是一个抽象类,实现了IOperationAsync和IContinueWithAsync两个接口。
IOperationAsync实现了异步操作,IContinueWithAsync实现了类似于Task的ContinueWith方法,在当前异步操作完成后继续进行的操作

IOperationAsync接口详解

public interface IOperationAsync
{
  IAsyncResult Invoke();
  void Wait();
  void CompletedCallBack(IAsyncResult ar);
  void CatchException(Exception exception);
}
  • Invoke():异步方法的调用
  • Wait():等待异步操作执行
  • CompletedCallBack():操作完成回调
  • CatchException():抓取异常

IContinueWithAsync接口详情

public interface IContinueWithAsync
{
  Operator Previous { get; set; }
  Operator Next { get; set; }
  Operator ContinueWithAsync(Action action);
  Operator ContinueWithAsync<TParameter>(Action<TParameter> action, TParameter parameter);
}

Previous:前一个操作
Next:下一个操作
ContinueWithAsync():异步继续操作

public abstract class Operator : IOperationAsync, IContinueWithAsync
{
  public IAsyncResult Middle;
  public readonly string Id;
  public Exception Exception { get; private set; }
  public Operator Previous { get; set; }
  public Operator Next { get; set; }
  protected Operator()
  {
    Id = Guid.NewGuid().ToString();
  }
  public abstract IAsyncResult Invoke();
  protected void SetAsyncResult(IAsyncResult result)
  {
    this.Middle = result;
  }
  public virtual void Wait()
  {
    if (!Middle.IsCompleted) Middle.AsyncWaitHandle.WaitOne();
  }
  public virtual void CompletedCallBack(IAsyncResult ar)
  {
  }
  public void CatchException(Exception exception)
  {
    this.Exception = exception;
  }
  protected Operator ContinueAsync()
  {
    if (Next != null) Next.Invoke();
    return Next;
  }
  public virtual Operator ContinueWithAsync(Action action)
  {
    Next = new ActionAsync(action);
    Next.Previous = this;
    return Next;
  }
  public virtual Operator ContinueWithAsync<TParameter>(Action<TParameter> action, TParameter parameter)
  {
    Next = new ActionAsync<TParameter>(action, parameter);
    Next.Previous = this;
    return Next;
  }
  public virtual Operator ContinueWithAsync<TResult>(Func<TResult> func)
  {
    Next = new FuncAsync<TResult>();
    Next.Previous = this;
    return Next;
  }
  public virtual Operator ContinueWithAsync<TParameter, TResult>(Func<TParameter, TResult> func,
    TParameter parameter)
  {
    Next = new FuncAsync<TParameter, TResult>(func, parameter);
    Next.Previous = this;
    return Next;
  }
}

无返回异步操作
ActionAsync

public class ActionAsync : Operator
{
  private readonly Action _action;
  protected ActionAsync()
  {
  }
  public ActionAsync(Action action)
    : this()
  {
    this._action = action;
  }
  public override IAsyncResult Invoke()
  {
    var middle = _action.BeginInvoke(CompletedCallBack, null);
    SetAsyncResult(middle);
    return middle;
  }
  public override void CompletedCallBack(IAsyncResult ar)
  {
    try
    {
      _action.EndInvoke(ar);
    }
    catch (Exception exception)
    {
      this.CatchException(exception);
    }
    ContinueAsync();
  }
}
public class ActionAsync<T> : ActionAsync
{
  public T Result;
  private readonly Action<T> _action1;
  protected readonly T Parameter1;
  public ActionAsync()
  {
  }
  public ActionAsync(T parameter)
  {
    this.Parameter1 = parameter;
  }
  public ActionAsync(Action<T> action, T parameter)
  {
    this._action1 = action;
    this.Parameter1 = parameter;
  }
  public override IAsyncResult Invoke()
  {
    var result = _action1.BeginInvoke(Parameter1, CompletedCallBack, null);
    SetAsyncResult(result);
    return result;
  }
  public override void CompletedCallBack(IAsyncResult ar)
  {
    try
    {
      _action1.EndInvoke(ar);
    }
    catch (Exception exception)
    {
      this.CatchException(exception);
    }
    ContinueAsync();
  }
}

有返回异步
FuncAsync实现了IFuncOperationAsync接口

IFuncOperationAsync

public interface IFuncOperationAsync<T>
{
  void SetResult(T result);
  T GetResult();
}
  • SetResult(T result):异步操作完成设置返回值
  • GetResult():获取返回值

1)、FuncAsync

public class FuncAsync<TResult> : Operator, IFuncOperationAsync<TResult>
{
private TResult _result;

public TResult Result
{
  get
  {
    if (!Middle.IsCompleted || _result == null)
    {
      _result = GetResult();
    }
    return _result;
  }
}
private readonly Func<TResult> _func1;
public FuncAsync()
{
}
public FuncAsync(Func<TResult> func)
{
  this._func1 = func;
}
public override IAsyncResult Invoke()
{
  var result = _func1.BeginInvoke(CompletedCallBack, null);
  SetAsyncResult(result);
  return result;
}
public override void CompletedCallBack(IAsyncResult ar)
{
  try
  {
    var result = _func1.EndInvoke(ar);
    SetResult(result);
  }
  catch (Exception exception)
  {
    this.CatchException(exception);
    SetResult(default(TResult));
  }
  ContinueAsync();
}
public virtual TResult GetResult()
{
  Wait();
  return this._result;
}
public void SetResult(TResult result)
{
  _result = result;
}
}
public class FuncAsync<T1, TResult> : FuncAsync<TResult>
{
protected readonly T1 Parameter1;
private readonly Func<T1, TResult> _func2;
public FuncAsync(Func<T1, TResult> action, T1 parameter1)
  : this(parameter1)
{
  this._func2 = action;
}
protected FuncAsync(T1 parameter1)
  : base()
{
  this.Parameter1 = parameter1;
}
public override IAsyncResult Invoke()
{
  var result = _func2.BeginInvoke(Parameter1, CompletedCallBack, null);
  SetAsyncResult(result);
  return result;
}
public override void CompletedCallBack(IAsyncResult ar)
{
  try
  {
    var result = _func2.EndInvoke(ar);
    SetResult(result);
  }
  catch (Exception exception)
  {
    CatchException(exception);
    SetResult(default(TResult));
  }
  ContinueAsync();
}
}

Asynchronous 异步操作封装
ActionAsync和FuncAsync为异步操作打下了基础,接下来最重要的工作就是通过这两个类执行我们的异步操作,为此我封装了一个异步操作类
主要封装了以下几个部分:

  • WaitAll(IEnumerable<Operator> operations):等待所有操作执行完毕
  • WaitAny(IEnumerable<Operator> operations):等待任意操作执行完毕
  • ActionAsync
  • FuncAsync
  • ContinueWithAction
  • ContinueWithFunc

后面四个包含若干个重载,这里只是笼统的代表一个类型的方法
WaitAll

public static void WaitAll(IEnumerable<Operator> operations)
{
foreach (var @operator in operations)
{
  @operator.Wait();
}
}

WaitAny

public static void WaitAny(IEnumerable<Operator> operations)
{
while (operations.All(o => !o.Middle.IsCompleted))
  Thread.Sleep(100);
}

等待时间可以自定义
ActionInvoke

public static Operator Invoke(Action action)
{
Operator operation = new ActionAsync(action);
operation.Invoke();
return operation;
}
public static Operator Invoke<T>(Action<T> action, T parameter)
{
Operator operation = new ActionAsync<T>(action, parameter);
operation.Invoke();
return operation;
}
public static Operator Invoke<T1, T2>(Action<T1, T2> action, T1 parameter1, T2 parameter2)
{
Operator operation = new ActionAsync<T1, T2>(action, parameter1, parameter2);
operation.Invoke();
return operation;
}

FuncInvoke

public static Operator Invoke<TResult>(Func<TResult> func)
{
Operator operation = new FuncAsync<TResult>(func);
operation.Invoke();
return operation;
}
public static Operator Invoke<TParameter, TResult>(Func<TParameter, TResult> func, TParameter parameter)
{
TParameter param = parameter;
Operator operation = new FuncAsync<TParameter, TResult>(func, param);
operation.Invoke();
return operation;
}
public static Operator Invoke<T1, T2, TResult>(Func<T1, T2, TResult> func, T1 parameter1, T2 parameter2)
{
Operator operation = new FuncAsync<T1, T2, TResult>(func, parameter1, parameter2);
operation.Invoke();
return operation;
}

ContinueWithAction

public static Operator ContinueWithAsync(IEnumerable<Operator>operators, Action action)
{
return Invoke(WaitAll, operators)
  .ContinueWithAsync(action);
}
public static Operator ContinueWithAsync<TParameter>(IEnumerable<Operator> operators, Action<TParameter> action, TParameter parameter)
{
return Invoke(WaitAll, operators)
  .ContinueWithAsync(action, parameter);
}

ContinueWithFunc

public static Operator ContinueWithAsync<TResult>(IEnumerable<Operator> operators,Func<TResult> func)
{
return Invoke(WaitAll, operators)
  .ContinueWithAsync(func);
}
public static Operator ContinueWithAsync<TParameter, TResult>(IEnumerable<Operator> operators,
Func<TParameter, TResult> func, TParameter parameter)
{
return Invoke(WaitAll, operators)
  .ContinueWithAsync(func, parameter);
}

这里有个bug当调用ContinueWithAsync后无法调用Wait等待,本来Wait需要从前往后等待每个异步操作,但是测试了下不符合预期结果。不过理论上来说应该无需这样操作,ContinueWithAsync只是为了当上一个异步操作执行完毕时继续执行的异步操作,若要等待,那不如两个操作放到一起,最后再等待依然可以实现。
前面的都是单步异步操作的调用,若需要对某集合进行某个方法的异步操作,可以foreach遍历

public void ForeachAsync(IEnumerbale<string> parameters)
{
  foreach(string p in parameters)
  {
    Asynchronous.Invoke(Tast,p);
  }
}
public void Test(string parameter)
{
  //TODO:做一些事
}

每次都需要去手写foreach,比较麻烦,因此实现类似于PLinq的并行计算方法实在有必要,不过有一点差别,PLinq是采用多核CPU进行并行计算,而我封装的仅仅遍历集合进行异步操作而已
ForeachAction

public static IEnumerable<Operator> Foreach<TParameter>(IEnumerable<TParameter> items, Action<TParameter> action)
{
  return items.Select(t => Invoke(action, t)).ToList();
}

ForeachFunc

public static IEnumerable<Operator> Foreach<TParameter, TResult>(IEnumerable<TParameter> items, Func<TParameter, TResult> func)
{
  return items.Select(parameter => Invoke(func, parameter)).ToList();
}

如何使用
无返回值异步方法调用

public void DoSomeThing()
{
//TODO:
}

通过Asynchronous.Invoke(DoSomeThing) 执行

public void DoSomeThing(string parameter)
{
//TODO:
}

通过Asynchronous.Invoke(DoSomeThing,parameter) 执行

有返回值异步方法调用

public string DoSomeThing()
{
//TODO:
}

通过Asynchronous.Invoke(()=>DoSomeThing())执行

public string DoSomeThing(string parameter)
{
//TODO:
}

通过Asynchronous.Invoke(()=>DoSomeThing(parameter))执行,或者也可以传入参数通过Asynchronous.Invoke(p=>DoSomeThing(p),parameter)

无返回值Foreach

public void Test
{
int[] parameters = {1,2,3,4,5};
Asynchronous.Foreach(parameters,Console.WriteLine);
}

有返回值Foreach

public void Test
{
int[] parameters = {1,2,3,4,5};
var operators = Asynchronous.Foreach(parameters,p=> p*2);
Asynchrous.WaitAll(operators);
Asynchronous.Foreach(operators.Cast<FuncAsync<int,int>>(),
  p=> Console.WriteLine(p.Result));
}

首先将集合每个值扩大2倍,然后输出
异步执行完再执行

public void Test
{
int[] parameters = {1,2,3,4,5};
var operators = Asynchronous.Foreach(parameters,p=> p*2);
Asynchrous.ContinueWithAsync(operators,Console.WriteLine,"执行完成");
}

每次执行完继续执行
可能有时候我们需要遍历一个集合,每个元素处理完成后我们需要输出XX处理完成

public void Test
{
int[] parameters = {1,2,3,4,5};
var operators = Asynchronous.Foreach(parameters,p=> p*2);
Asynchronous.Foreach(operators,o=>{
  o.ContinueWithAsync(()={
    //每个元素执行完时执行
    if(o.Exception != null)
    {
      //之前执行时产生未处理的异常,这里可以捕获到
    }
  });
});
}

可以实现链式异步操作

public void Chain()
{
Asynchronous.Invoke(Console.WriteLine,1)
.ContinueWithAsync(Console.WriteLine,2)
.ContinueWithAsync(Console.WriteLine,3)
}

这样会按步骤输出1,2,3
结束语

以上只是列出了部分重载方法,其他重载方法无非就是加参数,本质实际是一样的。

希望对大家的学习有所帮助,在这祝大家新年快乐,新的一年大家一起努力。

(0)

相关推荐

  • C#实现线程池的简单示例

    本文以实例演示了C#线程池的简单实现方法.程序中定义了一个对象类,用以包装参数,实现多个参数的传递.成员属性包括两个输入参数和一个输出参数.代码简单易懂,备有注释便于理解. 具体实现代码如下: using System; using System.Threading; //定义对象类,用以包装参数,实现多个参数的传递 class Packet { //成员属性包括两个输入参数和一个输出参数 protected internal String inval1; protected internal

  • C#实现向多线程传参的三种方式实例分析

    本文实例讲述了C#实现向多线程传参的三种方式.分享给大家供大家参考,具体如下: 从<C#高级编程>了解到给线程传递参数有两种方式,一种方式是使用带ParameterizedThreadStart委托参数的Thread构造函数,另一种方式是创建一个自定义类,把线程的方法定义为实例的方法,这样就可以初始化实例的数据,之后启动线程. 方式一:使用ParameterizedThreadStart委托 如果使用了ParameterizedThreadStart委托,线程的入口必须有一个object类型的

  • 解析C#多线程编程中异步多线程的实现及线程池的使用

    0.线程的本质 线程不是一个计算机硬件的功能,而是操作系统提供的一种逻辑功能,线程本质上是进程中一段并发运行的代码,所以线程需要操作系统投入CPU资源来运行和调度. 1.多线程: 使用多个处理句柄同时对多个任务进行控制处理的一种技术.据博主的理解,多线程就是该应用的主线程任命其他多个线程去协助它完成需要的功能,并且主线程和协助线程是完全独立进行的.不知道这样说好不好理解,后面慢慢在使用中会有更加详细的讲解. 2.多线程的使用: (1)最简单.最原始的使用方法:Thread oGetArgThre

  • C#线程池操作方法

    本文实例讲述了C#线程池操作方法.分享给大家供大家参考.具体如下: static void Main(string[] args) { //设置线程池中的线程数最大为1000, //第一个为工作者线程,第二个为I/O线程 ThreadPool.SetMaxThreads(1000, 1000); for (int i = 0; i < 10;i ) { ThreadPool.QueueUserWorkItem(new WaitCallback(ShowMessage), string.Forma

  • C#异步下载文件

    在C#当中,利用WebClient这个核心类,可以轻易的打造一个下载器.但是这里想要强调的是,我们用的是异步操作.所谓异步,是相对于同步的概念而言的.比如Web中的Ajax就是基于异步的.它能够提供良好的用户体验,让用户在进行操作时,不感觉到"卡"(不阻塞UI线程),能够同时进行其它的操作并能够随意的切换到任务界面.在下载文件时,如果文件过大,我们用同步的下载方式进行下载会感觉程序"假死",其实程序在后台不断的运行,但我们看不到下载的过程.所以这时候使用异步方法能够

  • C#多线程编程之使用ReaderWriterLock类实现多用户读与单用户写同步的方法

    本文实例讲述了C#多线程编程之使用ReaderWriterLock类实现多用户读与单用户写同步的方法.分享给大家供大家参考,具体如下: 摘要:C#提供了System.Threading.ReaderWriterLock类以适应多用户读/单用户写的场景.该类可实现以下功能:如果资源未被写操作锁定,那么任何线程都可对该资源进行读操作锁定,并且对读操作锁数量没有限制,即多个线程可同时对该资源进行读操作锁定,以读取数据. 使用Monitor或Mutex进行同步控制的问题:由于独占访问模型不允许任何形式的

  • C#异步绑定数据实现方法

    本文实例讲述了C#异步绑定数据实现方法.分享给大家供大家参考.具体如下: using System; using System.Collections.Generic; using System.Text; using System.Data.SqlClient; using System.Data; using System.Windows.Forms; namespace WindowsApplication2 { public class AsyncCallBackOpeartion {

  • C#多线程编程中的锁系统基本用法

    平常在多线程开发中,总避免不了线程同步.本篇就对net多线程中的锁系统做个简单描述. 目录 一:lock.Monitor      1:基础.      2: 作用域.      3:字符串锁.      4:monitor使用 二:mutex 三:Semaphore 四:总结 一:lock.Monitor 1:基础 Lock是Monitor语法糖简化写法.Lock在IL会生成Monitor. 复制代码 代码如下: //======Example 1=====             strin

  • C#异步执行任务的方法

    本文实例讲述了C#异步执行任务的方法.分享给大家供大家参考.具体如下: // 异步执行耗时任务(适合不需要等它的执行结果的场景,如发邮件.发短信) Task.Factory.StartNew( () => { try { // 需要异步执行的操作比如发邮件.发短信等 SendEmail(...); } catch { //不做任何处理,防止线程异常导致程序崩溃 } } ); 希望本文所述对大家的C#程序设计有所帮助.

  • C#基于委托实现多线程之间操作的方法

    本文实例讲述了C#基于委托实现多线程之间操作的方法.分享给大家供大家参考,具体如下: 有的时候我们要起多个线程,更多的时候可能会有某个线程会去操作其他线程里的属性. 但是线程是并发的,一般的调用是无法实现我们的要求的. 于是,我们在这里就可以用委托,代码如下 private delegate void DelegateInfo(); private delegate void DelegateIsEnd(); //这个是线程调用其他线程的方法 private void Dowork() { //

  • C#多线程学习之(四)使用线程池进行多线程的自动管理

    本文实例讲述了C#多线程学习之使用线程池进行多线程的自动管理.分享给大家供大家参考.具体如下: 在多线程的程序中,经常会出现两种情况: 一种情况:   应用程序中,线程把大部分的时间花费在等待状态,等待某个事件发生,然后才能给予响应 这一般使用ThreadPool(线程池)来解决: 另一种情况:线程平时都处于休眠状态,只是周期性地被唤醒 这一般使用Timer(定时器)来解决: ThreadPool类提供一个由系统维护的线程池(可以看作一个线程的容器),该容器需要 Windows 2000 以上系

  • C#线程池用法详细介绍

    介绍 .NET Framework提供了包含ThreadPool类的System.Threading 空间,这是一个可直接访问的静态类,该类对线程池是必不可少的.它是公共"线程池"设计样式的实现.对于后台运行许多各不相同的任务是有用的.对于单个的后台线种而言有更好的选项. 线程的最大数量.这是完全无须知道的.在.NET中ThreadPool的所有要点是它自己在内部管理线程池中线程.多核机器将比以往的机器有更多的线程.微软如此陈述"线程池通常有一个线程的最大数量,如果所有的线程

随机推荐