How to use Visual Studio - generated async WCF calls?
.net, asynchronous, c#, wcf
Solution
If you select 'Generate asynchrounous operations', you will get the 'old' behavior where you have to use callbacks.
If you want to use the new async/await syntax, you will have to select 'Generate task-based operations' (which is selected by default).
When using the default Wcf template, this will generate the following proxy code:
public System.Threading.Tasks.Task<string> GetDataAsync(int value) {
return base.Channel.GetDataAsync(value);
}
As you can see, there are no more callbacks. Instead a `Task<T>` is returned.
You can use this proxy in the following way:
public static async Task Foo()
{
using (ServiceReference1.Service1Client client = new ServiceReference1.Service1Client())
{
Task<string> t = client.GetDataAsync(1);
string result = await t;
}
}
You should mark the calling method with `async` and then use `await` when calling your service method.
Problem
My `OperationContract`: ``` public List<MessageDTO> GetMessages() { List<MessageDTO> messages = new List<MessageDTO>(); foreach (Message m in _context.Messages.ToList()) { messages.Add(new MessageDTO() { MessageID = m.MessageID, Content = m.Content, Date = m.Date, HasAttachments = m.HasAttachments, MailingListID = (int)m.MailingListID, SenderID = (int)m.SenderID, Subject = m.Subject }); } return messages; } ``` In Service Reference configuration I checked the option "Generate asynchronous operations". How do I use the generated `GetMessagesAsync()`? In the net I found examples that use `AsyncCallback`, however I'm not familiar with that. Is there a way to use it in some friendly way like `async` and `await` keywords in .NET 4.5? If not, what should I do to invoke the method asynchronously?