C#: Asynchronous method call

Just to store it! 😀

[code language=”csharp”]
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);
}
[/code]

Client example:
[code language=”csharp”]
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();
[/code]

Leave a Reply (Markdown is enabled)

Your email address will not be published. Required fields are marked *