2009-12-02 50 views
1
/// <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(); 
    } 
} 
+2

在http://stackoverflow.com/questions/405009/so-community-code-reviews中讨论了发布代码进行审查的可能性。看到它是真实的,我必须说我怀疑你会得到很多答案。至少你的同事将被支付审查代码。采用Q/A格式的想法是,几个人会从精心设计的答案中获得同样的问题和好处。有了评论,没有那么多...... – 2009-12-02 22:06:35

+0

我也怀疑过。我仍然想保持一段时间,以防万一灵魂有兴趣。 – ChaosPandion 2009-12-02 22:09:39

+1

你应该挑出你认为值得关注的问题,并制定一个通用的问题,这样我们可以更通用地回答问题,并且可能会遇到类似问题的人反复使用答案。 – 2009-12-02 22:09:59

回答

2

有问题。 “完成”需要不稳定,但不能使用MRE。您的超时代码可能会导致OverflowException异常。你正在翻译异常。

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

+0

我不认为在这种情况下完成需要变动。 http://stackoverflow.com/questions/59422/is-a-bool-read-write-atomic-in-c – ChaosPandion 2009-12-09 02:08:07