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

时间:2009-12-02 21:57:17

标签: 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();
    }
}

1 个答案:

答案 0 :(得分:3)

有问题。 “完成”需要不稳定,但不能,使用MRE。您的超时代码可能会在OverflowException上崩溃。你正在翻译例外。

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