Skip to content

Instantly share code, notes, and snippets.

@DVDPT
Created January 2, 2012 17:24
Show Gist options
  • Save DVDPT/1551438 to your computer and use it in GitHub Desktop.
Save DVDPT/1551438 to your computer and use it in GitHub Desktop.
C# 5.0 async wrapper for WCF services.
public class WcfAsyncWrapper<TEventArgs, TResult> where TEventArgs : AsyncCompletedEventArgs
{
private readonly bool _haveResult;
private readonly TaskCompletionSource<TResult> _taskCompletionSource;
private EventHandler<TEventArgs> _event;
public WcfAsyncWrapper(bool haveResult = true)
{
_haveResult = haveResult;
_taskCompletionSource = new TaskCompletionSource<TResult>();
}
public EventHandler<TEventArgs> Event
{
get
{
if (_event != null)
return _event;
return _event = GenericAsyncEvent;
}
}
private void GenericAsyncEvent(object sender, TEventArgs args)
{
if (args.Cancelled)
_taskCompletionSource.SetCanceled();
else if (args.Error != null)
_taskCompletionSource.SetException(args.Error);
///
/// Retrieve the Result
///
TResult result = default(TResult);
if (_haveResult)
{
var property = args.GetType().GetProperty("Result");
result = (TResult) property.GetValue(args, null);
}
_taskCompletionSource.SetResult(result);
}
public Task<TResult> Task
{
get { return _taskCompletionSource.Task; }
}
public static WcfAsyncWrapper<TArgs,object> FromVoidResult<TArgs>() where TArgs : AsyncCompletedEventArgs
{
return new WcfAsyncWrapper<TArgs, object>(false);
}
}
///
/// USAGE
///
var wcfAsyncWrapper = new WcfAsyncWrapper<GetDataFromRawInformationCompletedEventArgs, MediaInfoResult>();
Client.GetDataFromRawInformationCompleted += wcfAsyncWrapper.Event;
Client.GetDataFromRawInformationAsync(data);
var result = await wcfAsyncWrapper.Task;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment