简单实现C#异步操作

2019-12-26 17:28:50王旭

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:
}