/// <summary> /// 取出SocketAsyncEventArgs /// 如果取出失败,则new新的SocketAsyncEventArgs并返回 /// 当触发Completed事件后将自动回收 /// </summary> /// <returns></returns> public static SocketAsyncEventArgs Take() { SocketAsyncEventArgs eventArg; if (concurrentBag.TryTake(out eventArg) == false) { Interlocked.Increment(ref SendArgBag.totalInitCount); eventArg = new SocketAsyncEventArgs(); eventArg.Completed += (sender, e) => SendArgBag.Add(e); } return(eventArg); }
/// <summary> /// 异步发送数据 /// </summary> /// <param name="byteRange">数据范围</param> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="SocketException"></exception> public void Send(ByteRange byteRange) { if (byteRange == null) { throw new ArgumentNullException(); } if (this.IsConnected == false) { throw new SocketException((int)SocketError.NotConnected); } var sendArg = SendArgBag.Take(); sendArg.SetBuffer(byteRange.Buffer, byteRange.Offset, byteRange.Count); if (this.socket.SendAsync(sendArg) == false) { SendArgBag.Add(sendArg); } this.ExtraState.SetSended(byteRange.Count); }