private static void BatchSendRequestAdd(ITcpClientServer.ITcpEventClient client) { int v1 = new Random().Next(3, 9); int[] v2 = new int[] { 1, 2, 3, 4, 5 }; foreach (int i in v2) { Task.Factory.StartNew(() => { try { log4j.Info(string.Format("RequestAdd {0} {1}", v1, i)); //Task<Data.ResponseAdd> responseAdd = client.RequestAddAsync(v1, i); //log4j.Info(string.Format("ResponseAdd {0} + {1} = {2}", v1, i, responseAdd.Result.Result)); ResponseAdd response = client.RequestAdd(v1, i); log4j.Info(string.Format("responseAdd: {0} + {1} = {2}", v1, i, response.Result)); } catch (Exception ex) { log4j.Info(string.Format("RequestAdd {0} {1} {2}", v1, i, ex.Message)); } }); } }
public ResponseAdd RequestAdd(int timeOutMilliSec, params int[] param) { RequestAdd requestAdd = new RequestAdd { UUID = Guid.NewGuid().ToString() }; foreach (int p in param) { requestAdd.Param.Add(p); } // set a timeout on this call to server! // if we do not hv this timeout, calling this RequestAdd method will forever waiting if server never response! TaskCompletionSource <ResponseAdd> tcs = new TaskCompletionSource <ResponseAdd>(); //CancellationTokenSource ct = new CancellationTokenSource(timeOutMilliSec); // package TaskParallelLibrary CancellationTokenSource only hv empty constructor!! CancellationTokenSource ct = new CancellationTokenSource(); ResponseAddHandler rah = ((rpAdd) => { // only want the response UUID which is same as what we send if (rpAdd.UUID == requestAdd.UUID) { tcs.TrySetResult(rpAdd); } }); // when timeout occur, set Exception to TaskCompletionSource // also remove the callback from eventhandler ct.Token.Register(() => { OnResponseAdd -= rah; tcs.TrySetException(new TimeoutException("TimeOut " + timeOutMilliSec)); }, useSynchronizationContext: false); // use Rackspace.Threading.CancellationTokenSourceExtensions CancelAfter ct.CancelAfter(TimeSpan.FromMilliseconds(timeOutMilliSec)); OnResponseAdd += rah; //hook to the eventHandler //string sendCmd = "RequestAdd " + Newtonsoft.Json.JsonConvert.SerializeObject(requestAdd) + "\r\n"; string sendCmd = Cmd.TcsCommand.RequestAdd.ToString() + " " + Newtonsoft.Json.JsonConvert.SerializeObject(requestAdd) + "\r\n"; base.Send(Encoding.UTF8.GetBytes(sendCmd)); tcs.Task.Wait(); ResponseAdd responseAdd = tcs.Task.Result; OnResponseAdd -= rah; //after received our response, unhook it. we only expecting 1 response. return(responseAdd); }
/// <summary> /// Send command RequestAdd to server /// Receive a Data.ResponseAdd object /// - async method /// - will throw Exception "TimeOut" /// </summary> /// <param name="param"></param> /// <returns></returns> public async Task <ResponseAdd> RequestAddAsync(params int[] param) { RequestAdd requestAdd = new RequestAdd { UUID = Guid.NewGuid().ToString() }; foreach (int p in param) { requestAdd.Param.Add(p); } // set a timeout on this call to server! TaskCompletionSource <ResponseAdd> tcs = new TaskCompletionSource <ResponseAdd>(); const int timeOuts = 10000; //miliseconds CancellationTokenSource ct = new CancellationTokenSource(timeOuts); ResponseAddHandler rah = ((rpAdd) => { // only want the response UUID which is same as what we send if (rpAdd.UUID == requestAdd.UUID) { tcs.TrySetResult(rpAdd); } }); // when timeout occur, set Exception to TaskCompletionSource // also remove the callback from eventhandler ct.Token.Register(() => { OnResponseAdd -= rah; tcs.TrySetException(new TimeoutException("TimeOut " + timeOuts)); }, useSynchronizationContext: false); OnResponseAdd += rah; //hook to the eventHandler //string sendCmd = "RequestAdd " + Newtonsoft.Json.JsonConvert.SerializeObject(requestAdd) + "\r\n"; string sendCmd = Cmd.TcsCommand.RequestAdd.ToString() + " " + Newtonsoft.Json.JsonConvert.SerializeObject(requestAdd) + "\r\n"; base.Send(Encoding.UTF8.GetBytes(sendCmd)); ResponseAdd responseAdd = await tcs.Task; OnResponseAdd -= rah; //after received our response, unhook it. we only expecting 1 response. return(responseAdd); }
/// <summary> /// this will call by Command Class ResponseAdd /// </summary> /// <param name="responseAdd"></param> internal void PushToResponseAddHandler(ResponseAdd responseAdd) { //OnResponseAdd?.Invoke(responseAdd); OnResponseAdd?.BeginInvoke(responseAdd, (iar) => { log4j.Info("endInvoke"); var ar = (System.Runtime.Remoting.Messaging.AsyncResult)iar; var invokeMethod = (ResponseAddHandler)ar.AsyncDelegate; try { invokeMethod.EndInvoke(iar); } catch (Exception ex) { log4j.Error(invokeMethod.ToString(), ex); } }, null); }
public async Task <IActionResult> GetUsers([FromQuery] UserParams userParams) { ResponseAdd re = new ResponseAdd(); var currentLoggedInUser = await datingRepository.GetUser(int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)); userParams.Id = currentLoggedInUser.Id; if (!string.IsNullOrEmpty(currentLoggedInUser.Gender) && string.IsNullOrEmpty(userParams.Gender) && userParams.Likees == false && userParams.Likers == false) { userParams.Gender = currentLoggedInUser.Gender == "male" ? "female" : "male"; } PagedList <User> users = await datingRepository.GetUsers(userParams); Response.AddPaginationHeader(users.PageNumber, users.PageSize, users.TotalCount, users.TotalPages); var usersToReturn = mapper.Map <IEnumerable <UserList> >(users); re.ResponseBody = usersToReturn; return(Ok(re)); }
/// <summary> /// this will call by Command Class ResponseAdd /// </summary> /// <param name="responseAdd"></param> internal void PushToResponseAddHandler(ResponseAdd responseAdd) { OnResponseAdd?.Invoke(responseAdd); }
static void Main(string[] args) { System.Net.IPEndPoint endpoint = new IPEndPoint(new IPAddress(new byte[] { 127, 0, 0, 1 }), 2012); ITcpClientServer.ITcpEventClient client = new SPTcpClient(endpoint) { TimeOutMilliSec = 8000 }; client.OnResponseEcho += new ITcpClientServer.ResponseEchoHandler(message => { log4j.Info("Received echo: " + message); }); client.Start(); string cmd = ""; while (cmd != "q") { if (cmd == "1") { int a = 4; int b = 4; try { //Task<Data.ResponseAdd> response = client.RequestAddAsync(a, b); //log4j.Info(string.Format("responseAdd: {0} + {1} = {2}", a, b, response.Result.Result)); Task t1 = Task.Factory.StartNew(() => { ResponseAdd response = client.RequestAdd(a, b); log4j.Info(string.Format("responseAdd: {0} + {1} = {2}", a, b, response.Result)); }); //client.Send(Encoding.UTF8.GetBytes("RequestEcho abcdefg\r\n")); //client.Send(Encoding.UTF8.GetBytes(Data.Cmd.MyCommand.RequestEcho.ToString() + " abcdefg\r\n")); client.RequestEcho("aaasslslslsl"); t1.Wait(); } catch (AggregateException ae) { log4j.Info("catch aggregateException", ae); //ae.Handle((x) => //{ // Console.WriteLine(x.GetType().ToString()); // if(x is TimeoutException) // { // log4j.Info("TimeOut", x); // return true; // } // return true; //}); foreach (var e in ae.InnerExceptions) { Console.WriteLine(e.GetType().ToString()); if (e is TimeoutException) { log4j.Info("TimeOut", e); } } } catch (Exception ex) { log4j.Info("error", ex); } } else if (cmd == "3") { BatchSendRequestAdd(client); } //else if (cmd != "") //{ // // Server Command // // RequestEcho text // byte[] data = Encoding.UTF8.GetBytes(cmd + "\r\n"); // //client.Send(data, 0, data.Length); // log4j.Info("sending raw command: " + cmd); // client.Send(data); //} cmd = Console.ReadLine(); } client.Stop(); }