How to set a timeout value on StreamSocket's ConnectAsync()?

时间秒杀一切 提交于 2019-12-23 18:23:08

问题


In the Windows Phone 8.1 app I had to create my socket as follows. How can I change it so that it will timeout after a period that I can specify?

_socket = new StreamSocket();
await _socket.ConnectAsync(hostName, port.ToString(), SocketProtectionLevel.PlainSocket);

await _socket.InputStream.ReadAsync(frameLenData, frameLenData.Capacity, Windows.Storage.Streams.InputStreamOptions.None);

In my pre- Windows Phone code I'd create the Socket and set the timeout by testing _event.WaitOne(timeout), e.g.

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;
}

Can I set the timeout period for StreamSocket's ConnectAsync()? If so, how?


回答1:


Use a CancellationTokenSource and AsTask extension method.

var cts = new CancellationTokenSource();
cts.CancelAfter(2000); // cancel after 2 seconds

var connectAsync = _socket.ConnectAsync( ... );
var connectTask = connectAsync.AsTask(cts.Token);

await connectTask;   



回答2:


Since I do not have the reputation to add a comment I have to put it another answer.

Another way that doesn't require extra variables if they aren't required:

await socket.ConnectAsync(hostName, port).AsTask(new CancellationTokenSource(TimeSpan.FromSeconds(2)).Token);



回答3:


I do the following, which seems to work for me:

if (!_socket.ConnectAsync(uri, CancellationToken.None).Wait(timeout))
{
    // connect timed out
}


来源:https://stackoverflow.com/questions/25500649/how-to-set-a-timeout-value-on-streamsockets-connectasync

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!