我目前正在尝试了解c#5中的新关键字如何处理示例。我希望通过套接字连接发送一条消息,然后用一个监听器捕获一个答案。我真正被困的地方是我不能等待一个方法,这是一个例子:
private async void SubmitMessage(string strMessage)
{
try
{
using (StreamSocket objSocket = new StreamSocket())
{
IAsyncAction objAction = await objSocket.ConnectAsync(new HostName(TargetHostname), TargetPortservice);
objAction.Completed = delegate(IAsyncAction asyncAction, AsyncStatus asyncStatus)
{
BindListener(objSocket.Information.LocalPort, objSocket, strMessage);
};
}
}
catch (Exception objException)
{
Debug.WriteLine(objException.Message);
throw;
}
}
有谁知道如何等待这个?如果我删除'await'语法是正确的。谢谢你的帮助。
答案 0 :(得分:2)
当您使用await
时,您根本不需要使用IAsyncAction
,所以这样的事情应该有效:
private async Task SubmitMessage(string strMessage)
{
try
{
using (StreamSocket objSocket = new StreamSocket())
{
await objSocket.ConnectAsync(new HostName(TargetHostname), TargetPortservice);
BindListener(objSocket.Information.LocalPort, objSocket, strMessage);
}
}
catch (Exception objException)
{
Debug.WriteLine(objException.Message);
throw;
}
}
答案 1 :(得分:0)
对此不太了解,但会这样做吗?
IAsyncAction objAction =
objSocket.ConnectAsync(new HostName(TargetHostname), TargetPortservice);
await objAction;
//...