在Windows Phone 8.1应用程序中,我必须按如下方式创建我的套接字。如何更改它以便在我指定的时间段后它会超时?
_socket = new StreamSocket();
await _socket.ConnectAsync(hostName, port.ToString(), SocketProtectionLevel.PlainSocket);
await _socket.InputStream.ReadAsync(frameLenData, frameLenData.Capacity, Windows.Storage.Streams.InputStreamOptions.None);
在我的Windows Phone前代码中,我创建了Socket并通过测试_event.WaitOne(timeout)
来设置超时,例如
timeout = 5000;
_event = new ManualResetEvent(false);
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
bool bOperationFailed = false;
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = new DnsEndPoint(address, port);
_event.Reset();
_socket.ReceiveAsync(socketEventArg);
// Wait for completion
if (_event.WaitOne(timeout) == false)
{
Trace.trace("timed out");
return false;
}
我可以为StreamSocket
的ConnectAsync()
设置超时时间吗?如果是这样,怎么样?
使用CancellationTokenSource
和AsTask
扩展方法。
var cts = new CancellationTokenSource();
cts.CancelAfter(2000); // cancel after 2 seconds
var connectAsync = _socket.ConnectAsync( ... );
var connectTask = connectAsync.AsTask(cts.Token);
await connectTask;
由于我没有添加评论的声誉,我必须另外给出答案。
另一种不需要额外变量的方法:
await socket.ConnectAsync(hostName, port).AsTask(new CancellationTokenSource(TimeSpan.FromSeconds(2)).Token);
我做了以下,这似乎对我有用:
if (!_socket.ConnectAsync(uri, CancellationToken.None).Wait(timeout))
{
// connect timed out
}