【发布时间】:2015-12-28 01:20:16
【问题描述】:
Windows 商店应用程序至少可以说令人沮丧;与常规 .net 足够接近就会遇到麻烦。
我在使用 Tasks、await 和 Socket.ConnectAsync 时遇到的问题。
我有以下代码:
public async Task<string> Connect(string hostName, int portNumber)
{
string result = string.Empty;
// Create DnsEndPoint. The hostName and port are passed in to this method.
DnsEndPoint hostEntry = new DnsEndPoint(hostName, portNumber);
// Create a stream-based, TCP socket using the InterNetwork Address Family.
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Create a SocketAsyncEventArgs object to be used in the connection request
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = hostEntry;
// Inline event handler for the Completed event.
// Note: This event handler was implemented inline in order to make this method self-contained.
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate (object s, SocketAsyncEventArgs e)
{
// Retrieve the result of this request
result = e.SocketError.ToString();
// Signal that the request is complete, unblocking the UI thread
_clientDone.Set();
});
// Sets the state of the event to nonsignaled, causing threads to block
_clientDone.Reset();
// Make an asynchronous Connect request over the socket
await _socket.ConnectAsync(socketEventArg);
// Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
// If no response comes back within this time then proceed
_clientDone.WaitOne(TIMEOUT_MILLISECONDS);
return result;
}
我开始在应用程序中添加 Async / await 以防止出现 UI 问题。但是当我进入这个函数并将 Await 添加到
await _socket.ConnectAsync(socketEventArg);
我得到错误:
错误 CS1929“bool”不包含“GetAwaiter”的定义,并且最佳扩展方法重载“WindowsRuntimeSystemExtensions.GetAwaiter(IAsyncAction)”需要“IAsyncAction”类型的接收器
在查看 ConnectAsync 的文档时,看起来 ConnectAsync 应该支持 await...
不支持等待吗?
【问题讨论】:
标签: c# windows-store-apps async-await