如何同步异步方法?

时间:2009-11-21 16:53:10

标签: c# .net asynchronous synchronization iteration

var arguments = new double[] { 1d, 2d, 3d };
var result = arguments.Select(arg => Math.Sqrt(arg));

现在假设一个异步方法而不是Math.Sqrt(我不确定下面的方法是一个真正的async方法,但它的行为大致类似于一个)

public void BeginSqrt(Action<double> callback, double argument)
{
    Thread.Sleep(100);
    callback(Math.Sqrt(argument));
}

没有拆分代码就没有正确的方法来调用这种方法。因此,让我们将此异步方法与AutoResetEvent同步。我创建了一个帮助类:

public class Synchronizer<T, TResult>
{
    AutoResetEvent _autoResetEvent = new AutoResetEvent(false);
    TResult _result;

    public TResult Execute(Action<Action<TResult>,T> beginMethod, T argument)
    {
        beginMethod(Callback, argument);
        _autoResetEvent.WaitOne();
        return _result;
    }

    void Callback(TResult result)
    {
        _result = result;
        _autoResetEvent.Set();
    }
}

通过这门课,我们可以:

var synchronizer = new Synchronizer<double, double>();
var result = arguments.Select(arg => synchronizer.Execute(BeginSqrt, arg));

我在思考问题的几分钟内创建了这个解决方案。有一个本地替代品吗?我确信我的解决方案有错误,因为它错过了一些锁。有一个更加成熟的图书馆可以做到吗?

1 个答案:

答案 0 :(得分:0)

使用Parallel LINQ,您可以写:

var arguments = new double[] { 1d, 2d, 3d };
var result = arguments.AsParallel().Select(arg => Math.Sqrt(arg));

这将并行计算每个参数的平方根。 这是你想要实现的目标吗?