1

我目前正在尝试了解 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;
        }
    }

有谁知道如何等待这个?如果我删除“等待”,则语法是正确的。谢谢你的帮助。

4

2 回答 2

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;
    }
}
于 2013-01-20T01:30:05.023 回答
0

对此不太了解,但这会吗?

IAsyncAction objAction = 
 objSocket.ConnectAsync(new HostName(TargetHostname), TargetPortservice);
await objAction;
//...
于 2013-01-20T01:18:05.330 回答