/// <summary> /// 设置行为 /// </summary> /// <param name="setType">行为类型</param> /// <param name="bytes">数据值</param> public void SetAction(SetTypes setType, byte[] bytes) { switch (setType) { case SetTypes.SetReturnReult: this.SetResult(bytes); break; case SetTypes.SetReturnException: var message = bytes == null ? string.Empty : Encoding.UTF8.GetString(bytes); var remoteException = new RemoteException(message); this.taskSource.TrySetException(remoteException); break; case SetTypes.SetTimeoutException: var timeoutException = new TimeoutException(); this.taskSource.TrySetException(timeoutException); break; case SetTypes.SetShutdownException: var shutdownException = new SocketException(SocketError.Shutdown.GetHashCode()); this.taskSource.TrySetException(shutdownException); break; } }
/// <summary> /// 设置Api行为返回的任务异常 /// </summary> /// <param name="taskSetActionTable">任务行为表</param> /// <param name="requestContext">请求上下文</param> /// <returns></returns> public static bool SetApiActionTaskException(TaskSetterTable <long> taskSetActionTable, RequestContext requestContext) { var taskSetAction = taskSetActionTable.Remove(requestContext.Packet.Id); if (taskSetAction == null) { return(true); } var exceptionBytes = requestContext.Packet.Body; var message = exceptionBytes == null ? string.Empty : Encoding.UTF8.GetString(exceptionBytes); var exception = new RemoteException(message); return(taskSetAction.SetException(exception)); }
/// <summary> /// 创建新的SetAction /// </summary> /// <typeparam name="T"></typeparam> /// <param name="taskSource">任务源</param> /// <param name="serializer">序列化工具</param> /// <returns></returns> private static Action <SetTypes, byte[]> NewSetAction <T>(TaskCompletionSource <T> taskSource, ISerializer serializer) { Action <SetTypes, byte[]> setAction = (setType, bytes) => { if (setType == SetTypes.SetReturnReult) { if (bytes == null || bytes.Length == 0) { taskSource.TrySetResult(default(T)); return; } try { var result = (T)serializer.Deserialize(bytes, typeof(T)); taskSource.TrySetResult(result); } catch (SerializerException ex) { taskSource.TrySetException(ex); } catch (Exception ex) { taskSource.TrySetException(new SerializerException(ex)); } } else if (setType == SetTypes.SetReturnException) { var message = bytes == null ? string.Empty : Encoding.UTF8.GetString(bytes); var exception = new RemoteException(message); taskSource.TrySetException(exception); } else if (setType == SetTypes.SetTimeoutException) { var exception = new TimeoutException(); taskSource.TrySetException(exception); } else if (setType == SetTypes.SetShutdownException) { var exception = new SocketException(SocketError.Shutdown.GetHashCode()); taskSource.TrySetException(exception); } }; return(setAction); }