Brunov's blog

Sergey Vyacheslavovich Brunov's blog

C#: Asynchronous method call

2011-12-20 10:44:56 Moscow time

Just to store it.

public static IAsyncResult RunAsync(
    Func<AsyncCallback, object, IAsyncResult> begin,
    Action<IAsyncResult> end,
    Action<Action> callback)
{
    return begin(ar =>
    {
    try
    {
        end(ar);
        callback(delegate { });
    }
    catch (Exception ex)
    {
        callback(() => { throw ex; });
    }
    }, null);
}

public static IAsyncResult RunAsync<T>(
    Func<AsyncCallback, object, IAsyncResult> begin,
    Func<IAsyncResult, T> end,
    Action<Func<T>> callback)
{
    return begin(ar =>
    {
    try
    {
        T result = end(ar);
        callback(() => result);
    }
    catch (Exception ex)
    {
        callback(() => { throw ex; });
    }
    }, null);
}

Client example:

Action printAction = () =>
{
    Console.WriteLine("Hello, World!");
    Thread.Sleep(10000);
    // throw new InvalidOperationException();
    Console.WriteLine("Bye!");
};

IAsyncResult asyncResult = RunAsync(printAction.BeginInvoke, printAction.EndInvoke,
(func) =>
    {
    func();
    });

asyncResult.AsyncWaitHandle.WaitOne();

Tags: .net Action async C#