如何使用 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 中的 async
和 await
关键字?如果不是,我该怎么做才能异步调用该方法?
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.
如果要使用新的 async/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);
}
如您所见,不再有回调.而是返回一个 Task
.
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;
}
}
你应该用 async
标记调用方法,然后在调用你的服务方法时使用 await
.
You should mark the calling method with async
and then use await
when calling your service method.
这篇关于如何使用 Visual Studio - 生成的异步 WCF 调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!