private void SendCore(Func<IEnumerable<Zongsoft.Common.Buffer>> pack, object asyncState) { //通知子类准备开始发送数据,如果没有准备好则直接退出。 //通常子类会重写该方法进行发送前的各项准备工作,譬如自动网络连接等。 if(!this.PrepareSend(asyncState)) return; //首先本地保存对全局对象的引用,以防止其他线程修改全局变量的引用 var socket = _socket; if(socket == null) return; //生成一个唯一的流水号 var sequenceId = Interlocked.Increment(ref _sequenceId); var state = new PackingState(); //将待发送的包加入到本地正在发送的包计数器中 _sendingCounter[sequenceId] = state; foreach(var buffer in pack()) { state.CountOfPack++; //从异步事件参数池中取出一个可用的对象出来 var asyncArgs = _sendingAsyncArgsPool.GetObject(); //设置要发送的缓存区状态 asyncArgs.SetBuffer(buffer.Value, buffer.Offset, buffer.Count); //设置用户自定义对象 asyncArgs.UserToken = new SendingToken(sequenceId, asyncState); try { //等待TCP协议栈缓存是否可用 _sendingBlocking.Wait(); if(!socket.SendAsync(asyncArgs)) this.OnSendCompleted(asyncArgs); } catch(ObjectDisposedException) { this.RaiseSendFailed((SendingToken)asyncArgs.UserToken); return; } catch(SocketException) { this.RaiseSendFailed((SendingToken)asyncArgs.UserToken); return; } } //设置当前发送状态为打包完成 state.IsPacked = true; if(this.EnsureSent(sequenceId)) this.OnSent(new SentEventArgs(this, asyncState)); }
private void SendCore(Func <IEnumerable <Zongsoft.Common.Buffer> > pack, object asyncState) { //通知子类准备开始发送数据,如果没有准备好则直接退出。 //通常子类会重写该方法进行发送前的各项准备工作,譬如自动网络连接等。 if (!this.PrepareSend(asyncState)) { return; } //首先本地保存对全局对象的引用,以防止其他线程修改全局变量的引用 var socket = _socket; if (socket == null) { return; } //生成一个唯一的流水号 var sequenceId = Interlocked.Increment(ref _sequenceId); var state = new PackingState(); //将待发送的包加入到本地正在发送的包计数器中 _sendingCounter[sequenceId] = state; foreach (var buffer in pack()) { state.CountOfPack++; //从异步事件参数池中取出一个可用的对象出来 var asyncArgs = _sendingAsyncArgsPool.GetObject(); //设置要发送的缓存区状态 asyncArgs.SetBuffer(buffer.Value, buffer.Offset, buffer.Count); //设置用户自定义对象 asyncArgs.UserToken = new SendingToken(sequenceId, asyncState); try { //等待TCP协议栈缓存是否可用 _sendingBlocking.Wait(); if (!socket.SendAsync(asyncArgs)) { this.OnSendCompleted(asyncArgs); } } catch (ObjectDisposedException) { this.RaiseSendFailed((SendingToken)asyncArgs.UserToken); return; } catch (SocketException) { this.RaiseSendFailed((SendingToken)asyncArgs.UserToken); return; } } //设置当前发送状态为打包完成 state.IsPacked = true; if (this.EnsureSent(sequenceId)) { this.OnSent(new SentEventArgs(this, asyncState)); } }