DotNet Programming World

Thursday, November 10, 2011

Using Extention Methods

  

public static class WcfServiceClient where TProxy : ICommunicationObject, IDisposable, new()
{
///
/// Which allows writing this kind of code:
/// Service.Using(svc => svc.PerformOperation());
/// Or:
/// Service.Using(svc =>
/// {
/// var result = svc.PerformOperation();
/// ProcessResult(result);
/// });
///

///
public static void Using(Action action)
{
var proxy = new TProxy();
System.Net.ServicePointManager.Expect100Continue = false;
bool success = false;

try
{
action(proxy);
proxy.Close();
success = true;
}
finally
{
if (!success)
{
proxy.Abort();
}
}
}

public static TResult Using(Func func)
{
var proxy = new TProxy();
bool success = false;

try
{
TResult result = func(proxy);
proxy.Close();
success = true;

return result;
}
finally
{
if (!success)
{
proxy.Abort();
}
}
}
}

0 Comments:

Post a Comment

<< Home