如何使用Visual Studio - 产生异步调用WCF? [英] How to use Visual Studio - generated async WCF calls?
问题描述
我的 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;
}
在服务的参考配置我查了选项生成异步操作。如何使用生成的 GetMessagesAsync()
?中网我发现,使用的AsyncCallback
的例子,但我不熟悉。有没有办法使用它像一些友好的方式异步
办法和等待
关键字.NET 4.5?如果不是这样,我应该怎么办异步调用的方法?
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?
推荐答案
如果您选择生成 - 异步操作,你会得到'老'的行为,你必须使用回调。
If you select 'Generate asynchrounous operations', you will get the 'old' behavior where you have to use callbacks.
如果您要使用新的异步/的await语法,你将不得不选择生成基于任务的操作。(这是默认选择)
If you want to use the new async/await syntax, you will have to select 'Generate task-based operations' (which is selected by default).
在使用默认WCF模板,这样会生成以下代理代码:
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);
}
正如你所看到的,有没有更多的回调。取而代之的是任务< T>
返回
您可以通过以下方式使用这个代理:
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;
}
}
您应该标记为<$ C $调用的方法C>异步,然后用等待
调用服务方法时。
You should mark the calling method with async
and then use await
when calling your service method.
这篇关于如何使用Visual Studio - 产生异步调用WCF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!