Glad you are doing things asynchronously in WPF. That's how it should be done, even though you have the option of doing it synchronously.
Yes, there is a way to do this. The "Cocktail Async Pack for VS 2012" defines AsOperationResult for Task and Task<T>. Assuming that you are not doing this in VS 2012 just yet, you can grab TaskFns.cs from Github and drop it into your project. Once there you can do the following:
yield return Task.Factory.StartNew(() => DoSomethingSynchronous()).AsOperationResult();
The same file also defines overloads for Task.OnComplete() and Task<T>.OnComplete() to do the onSuccess, onFail callbacks. So your StartService method would look something like this:
public OperationResult StartService(string serviceName, Action onSuccess, Action<Exception> onFail)
{
return Task.Factory.StartNew(() => DoStartService(serviceName))
.OnComplete(onSuccess, onFail);
.AsOperationResult();
}
You can even return a value at the end from your task back the the UI thread. For example if you want to return true or false to indicate whether the service started or not, you can do that like this:
public bool DoStartService(string serviceName)
{
......
return resultValue;
}
public OperationResult<bool> StartService(string serviceName, Action<bool> onSuccess, Action<Exception> onFail)
{
return Task.Factory.StartNew(() => DoStartService(serviceName)) // This will now return Task<bool>
.OnComplete(onSuccess, onFail);
.AsOperationResult();
}
Edited by mgood - 26-Jul-2012 at 10:54am