2013-01-11 33 views
6

可能重复:
Brief explanation of Async/Await in .Net 4.5C#5异步/等待最简单的说明

我在C#中被编程有一段时间了,但我不能让我围绕如何头新的异步/等待语言功能的作品。

我写了这样的功能:

public async Task<SocketError> ConnectAsync() { 
    if (tcpClient == null) CreateTCPClient(); 
    if (tcpClient.Connected) 
     throw new InvalidOperationException("Can not connect client: IRCConnection already established!"); 

    try { 
     Task connectionResult = tcpClient.ConnectAsync(Config.Hostname, Config.Port); 
     await connectionResult; 
    } 
    catch (SocketException ex) { 
     return ex.SocketErrorCode; 
    } 

    return SocketError.Success; 
} 

但显然,没有点到这一点,对不对?因为我正在等待紧接着的行上的TcpClient.ConnectAsync的结果。

但我想写我的ConnectAsync()函数,以便它本身可以用另一种方法等待。这是正确的方法吗?我有点失落。

await tcpClient.ConnectAsync(Config.Hostname, Config.Port); 

因为等待的“任务”回归工程没有返回,除非函数有一个任务结果::)

+1

如果你想有一个只有成功/失败的“异步”方法(没有“结果”值),然后返回“任务”而不是“任务”。在.NET中返回错误代码不是正常的做法。 –

+0

Stephen:我实际上想返回SocketError(如果有的话),或者SocketError.Success(如果没有的话)。然而,你是否认为只是让任何SocketException被传播给调用者会更好? – Xenoprimate

+0

@Migig是的,这就是他所说的。 – Servy

回答

4

我希望你所遇到的yield return语法来创建一个迭代器。它暂停执行,然后在需要下一个元素时继续。你可以想到await做一些非常相似的事情。等待异步结果,然后该方法的其余部分继续。当然,它不会被阻挡,因为它会等待。

+0

是的,我有。按照我理解的方式,收益回报只会根据需要返回集合中的元素。那么你是否说tcpClient.ConnectAsync()方法不会阻塞,直到从程序的另一个区域访问tcpClient上的某个字段? – Xenoprimate

+0

@Motig - 在这种情况下,直到异步操作的结果可用。 – manojlds

2

除了我相信这是语法似乎不错。

这里是microsoft

private async void button1_Click(object sender, EventArgs e) 
{ 
    // Call the method that runs asynchronously. 
    string result = await WaitAsynchronouslyAsync(); 

    // Call the method that runs synchronously. 
    //string result = await WaitSynchronously(); 

    // Display the result. 
    textBox1.Text += result; 
} 

// The following method runs asynchronously. The UI thread is not 
// blocked during the delay. You can move or resize the Form1 window 
// while Task.Delay is running. 
public async Task<string> WaitAsynchronouslyAsync() 
{ 
    await Task.Delay(10000); 
    return "Finished"; 
} 

// The following method runs synchronously, despite the use of async. 
// You cannot move or resize the Form1 window while Thread.Sleep 
// is running because the UI thread is blocked. 
public async Task<string> WaitSynchronously() 
{ 
    // Add a using directive for System.Threading. 
    Thread.Sleep(10000); 
    return "Finished"; 
} 
0

这样的事情很明显的例子:

  • tcpClient.ConnectAsync(Config.Hostname, Config.Port)将异步运行;
  • await connectionResult之后执行将回调到ConnectAsync方法的调用者;
  • 然后await connectionResult将完成它的异步工作,你的方法的其余部分将被执行(如回调);

祖先此功能:

Simplified APM with the AsyncEnumerator

More AsyncEnumerator Features