代码之家  ›  专栏  ›  技术社区  ›  ChaosPandion

这是否正确使用了Socket类的异步能力?

  •  1
  • ChaosPandion  · 技术社区  · 16 年前
    /// <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();
        }
    }
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Hans Passant    16 年前

    有问题。”“已完成”需要是易变的,但不能是,使用MRE。超时代码可能因OverflowException而崩溃。你在翻译例外。

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

    推荐文章