/// <summary> /// 异步发送 /// </summary> /// <param name="buffer">字节数组</param> /// <param name="offset">起始偏移量</param> /// <param name="size">字节数</param> public void Write(Byte[] buffer, Int32 offset, Int32 size) { // 用户定义对象 AsyncWriteStateObject State = new AsyncWriteStateObject { // 将事件状态设置为非终止状态,导致线程阻止 eventDone = new ManualResetEvent(false), stream = Stream, exception = null, }; Byte[] BytesArray; Int32 Length = size + 4; // 加入4字节长度信息后的总长度 BytesArray = new Byte[Length]; Array.Copy(BitConverter.GetBytes(Length), BytesArray, 4); Array.Copy(buffer, offset, BytesArray, 4, size); // 写入加长度信息头的数据 Stream.BeginWrite(BytesArray, 0, BytesArray.Length, new AsyncCallback(AsyncWriteCallback), State); // 等待操作完成信号 if (State.eventDone.WaitOne(Stream.WriteTimeout, false)) { // 接收到信号 if (State.exception != null) { throw State.exception; } } else { // 超时异常 throw new TimeoutException(); } }
/// <summary> /// 异步写入回调函数 /// </summary> /// <param name="ar">异步操作结果</param> private static void AsyncWriteCallback(IAsyncResult ar) { AsyncWriteStateObject State = ar.AsyncState as AsyncWriteStateObject; try { // 异步写入结束 State.stream.EndWrite(ar); } catch (Exception e) { // 异步连接异常 State.exception = e; } finally { // 将事件状态设置为终止状态,线程继续 State.eventDone.Set(); } }
/// <summary> /// 异步发送 /// </summary> /// <param name="buffer">字节数组</param> /// <param name="offset">起始偏移量</param> /// <param name="size">字节数</param> public void Write(Byte[] buffer, Int32 offset, Int32 size) { // 用户定义对象 AsyncWriteStateObject State = new AsyncWriteStateObject { // 将事件状态设置为非终止状态,导致线程阻止 eventDone = new ManualResetEvent(false), stream = Stream, exception = null, }; Byte[] BytesArray; Int32 Length = size + 4; // 加入4字节长度信息后的总长度 BytesArray = new Byte[Length]; Array.Copy(BitConverter.GetBytes(Length), BytesArray, 4); Array.Copy(buffer, offset, BytesArray, 4, size); // 写入加长度信息头的数据 Stream.BeginWrite(BytesArray, 0, BytesArray.Length, new AsyncCallback(AsyncWriteCallback), State); // 等待操作完成信号 if (State.eventDone.WaitOne(Stream.WriteTimeout, false)) { // 接收到信号 if (State.exception != null) throw State.exception; } else { // 超时异常 throw new TimeoutException(); } }