开发者

How to synchronize asynchronous methods?

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

Now imagine a asynchronous method instead of Math.Sqrt (i'm not sure the method below is a true async method, but it behaves approximately like one)

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

There is no right way of calling such method without splitting the code. So let's synchronize this asynchronous method with AutoResetEvent. I created a helper class:

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

    开发者_JAVA百科void Callback(TResult result)
    {
        _result = result;
        _autoResetEvent.Set();
    }
}

With this class we can:

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

This solution I created in a few minutes while I was thinking about the problem. There is a native alternative to this? I am sure my solutions has bugs, since it misses some locks. There is a more proven library to do that?


Using Parallel LINQ you can write:

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

This would calculate the square root of each argument in parallel. Is that what you're trying to achieve?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜