/// <summary> /// 查询并获得回执 /// </summary> /// <typeparam name="T1">请求类</typeparam> /// <typeparam name="T2">返回类</typeparam> /// <param name="req">请求参数</param> /// <param name="wait_id">等待这个包回传</param> /// <param name="reply">回传</param> /// <returns></returns> private ErrorDef req_wait_reply <T1, T2>(T1 req, MsgID wait_id, out T2 reply) where T1 : IMessage <T1> where T2 : IMessage <T2>, new() { reply = default(T2); ErrorDef result_err = ErrorDef.Ok; byte[] req_bytes = Codec.Encode(req); result_err = write(req_bytes); if (result_err != ErrorDef.Ok) { return(result_err); } //超过这个时间 int timeout = 10000; result_err = ErrorDef.TimeoutErr; T2 _reply = default(T2); Action <MsgID, byte[]> action = (msg_id, data) => { MessageParser <T2> parser = new MessageParser <T2>(() => new T2()); _reply = parser.ParseFrom(data); timeout = 0; result_err = ErrorDef.Ok; }; WaitPack pack = new WaitPack(); pack.action = action; pack.msg_id = wait_id; lock (wait_pack_look) { wait_pack.AddLast(pack); } Thread wait_th = new Thread((o) => { while (timeout > 0) { Thread.Sleep(50); timeout -= 50; } }); wait_th.Start(); wait_th.Join(); lock (wait_pack_look) { wait_pack.Remove(pack); } reply = _reply; return(result_err); }
/// <summary> /// 查询并获得回执 /// </summary> /// <typeparam name="T1">请求类</typeparam> /// <typeparam name="T2">返回类</typeparam> /// <param name="req">请求参数</param> /// <param name="wait_id">等待这个包回传</param> /// <param name="reply">回传</param> /// <returns></returns> private ErrorDef req_wait_reply <T1, T2>(T1 req, MsgID wait_id, out T2 reply) { reply = default(T2); ErrorDef result_err = ErrorDef.Ok; byte[] req_bytes = Codec.Encode(req); result_err = write(req_bytes); if (result_err != ErrorDef.Ok) { return(result_err); } //超过这个时间 int timeout = 3000; result_err = ErrorDef.TimeoutErr; T2 _reply = default(T2); Action <MsgID, string> action = (msg_id, content) => { _reply = JsonConvert.DeserializeObject <T2>(content); timeout = 0; result_err = ErrorDef.Ok; }; WaitPack pack = new WaitPack(); pack.action = action; pack.msg_id = wait_id; lock (wait_pack_look) { wait_pack.AddLast(pack); } Thread wait_th = new Thread((o) => { while (timeout > 0) { Thread.Sleep(50); timeout -= 50; } }); wait_th.Start(); wait_th.Join(); lock (wait_pack_look) { wait_pack.Remove(pack); } reply = _reply; return(result_err); }