Reputation: 7517
I apologize if a variation of this question has been asked before, but I'm struggling to find an answer that applies to my current situation.
I am working on a project where I've been asked to expose the operations of a Task based provider via a WCF service. The provider interface explicitly defines Task<T>
as the return type of each method, here's an example:
public interface IContactProvider
{
Task<IEnumerable<Contact>> GetAllContacts();
}
In an attempt to expose this as a WCF service, I've basically defined a "synchronous" version of the provider interface to use as a service contract resulting in a service implementation that looks like this:
public class ContactService : IContactService
{
private IContactProvider contactProvider;
public IEnumerable<Contact> GetAllContacts()
{
return contactProvider.GetAllContacts().Result;
}
}
My instinct tells me that I'm doing something wrong here and that I should be "waiting" for the Result
to be available some other way. Is there a better way to do this?
Upvotes: 1
Views: 783
Reputation: 6361
What you're doing should work fine (Result
will block until the task completes), but are you using .NET 4.5? If so you could simply declare your service operation contract to return the async Task<T>
directly. That way your clients would automatically get the option to call it synchronously or asynchronously (via the generated service client).
Here's a post I found more useful than the MSDN docs: http://blog.vuscode.com/malovicn/archive/2012/01/21/what-is-new-in-wcf-in-net-4-5-taskt-and-async.aspx
Upvotes: 2