c# - 这是否正确使用了Socket类的异步功能?

标签 c# sockets asynchronous

/// <summary></summary>
private Byte[] _ReceiveBytes(Int32 size)
{
    MemoryStream memory = null;  
    SocketAsyncEventArgs args = null;
    EventHandler<SocketAsyncEventArgs> completed = null;
    Exception exception = null;
    Int32 last_update = Environment.TickCount;
    Boolean finished = false;
    Int32 count = 0;
    Int32 received = 0;

    completed = new EventHandler<SocketAsyncEventArgs>((s, e) =>
    {
        try
        {
            count = e.BytesTransferred;
            last_update = (count > 0 ? Environment.TickCount : last_update);
            memory.Write(e.Buffer, 0, count);
            received += count;
            finished = (received == size);
            if (!finished)
            {
                count = Math.Min(_ChunkSize, size - received);
                args.SetBuffer(new Byte[count], 0, count);
                if (!_Socket.ReceiveAsync(e))
                {
                    completed(s, e);
                }
            }
        }
        catch (Exception ex)
        {
            exception = ex;
        }
    });

    using (memory = new MemoryStream())
    using (args = new SocketAsyncEventArgs())
    {
        count = Math.Min(_ChunkSize, size - received);
        args.SetBuffer(new Byte[count], 0, count);
        args.Completed += completed;

        if (!_Socket.ReceiveAsync(args))
        {
            completed(_Socket, args);
        }

        while (!finished)
        {
            Thread.Sleep(_SleepTimeSpan);
            if (exception != null)
            {
                throw new Exception(_ReceiveExceptionMessage, exception);
            }
            else if (!finished && Environment.TickCount - last_update > _ReceiveTimeout)
            {
                throw new TimeoutException(_TimeoutExceptionMessage);
            }
        }

        return memory.ToArray();
    }
}

最佳答案

有问题。使用MRE,“完成”必须是易变的,但不能如此。您的超时代码可能会在OverflowException上崩溃。您正在翻译异常(exception)。

但是这种方法没有意义,等待异步操作完成没有任何意义。使用Socket.ReceiveTimeout获取超时异常。

关于c# - 这是否正确使用了Socket类的异步功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1836109/

相关文章:

java - 服务器发起的客户端-服务器通信

c++ - Protocol Buffer 和实际传输选项 - 套接字或中间件

javascript - Promise返回值和嵌套

c# - EF6 异步方法困惑

iphone - 从同步请求切换到带有图片上传的异步请求?

c# - 使用 Unity 有条件地注入(inject)依赖项

c# - 系统参数异常 : The table type parameter must have a valid type name

c# - 是否可以只在 ASP.Net 中处理 404 错误?

c# - Triplet 类的用途是什么?它与元组有关吗?

linux - accept() 失败时 sockaddr 的状态是什么