UWP套接字:客户端套接字StoreAsync操作在套接字关闭时不会中断

时间:2018-02-23 10:42:28

标签: sockets networking uwp

在Windows 10上使用UWP套接字时,我看到一种恼人的行为,当套接字上调用CancelIOAsyncDispose时,挂起的异步写操作不会被中断。下面是一些演示此问题的示例代码。

基本上,while循环循环2次迭代,直到发送套接字缓冲区已满(服务器端连接不会故意读取数据以证明问题)。下一个await socket.StoreAsync()操作最终无限期地等待,它不会因插座的关闭而中断。

有关如何中断待处理StoreAsync的任何想法?

由于 贝努瓦。

public sealed partial class MainPage : Page
{
private StreamSocket socket;
private StreamSocket serverSocket;

public MainPage()
{
    this.InitializeComponent();

    StreamSocketListener listener = new StreamSocketListener();
    listener.ConnectionReceived += OnConnection;
    listener.Control.KeepAlive = false;
    listener.BindServiceNameAsync("12345").GetResults();
}

async private void Connect_Click(object sender, RoutedEventArgs e)
{
    socket = new StreamSocket();
    socket.Control.KeepAlive = false;
    await socket.ConnectAsync(new HostName("localhost"), "12345");
    DataWriter writer = new DataWriter(socket.OutputStream);
    try
    {
        while(true)
        {
            writer.WriteBytes(new byte[1000000]);
            await writer.StoreAsync();
            Debug.WriteLine("sent bytes");
        }
    }
    catch(Exception ex)
    {
        Debug.WriteLine("sent failed : " + ex.ToString());
    }
}

async private void Close_Click(object sender, RoutedEventArgs e)
{
    //
    // Closing the client connection with a pending write doesn't cancel the pending write.
    //
    Debug.WriteLine("Closing Client Connection");
    await socket.CancelIOAsync();
    socket.Dispose();
}

private void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
    System.Diagnostics.Debug.WriteLine("Received connection");
    serverSocket = args.Socket;
}
}

0 个答案:

没有答案