两年前我遇到一个难题:
https://q.cnblogs.com/q/78177
WebAPI中使用socket如果在server端回复了再返回值?
现在终于做出一种实现了:
[HttpGet] public ApiActionResult OnceBackDemo() { var result = new ApiActionResult() { Success = false, Result = null, Message = "操作失败。" }; System.Threading.ManualResetEvent mre = new System.Threading.ManualResetEvent(false); mre.Reset(); Random rm = new Random(); Action<Stopwatch> task = (sw) => { sw.Start(); int rm_val = rm.Next(1000); System.Threading.Thread.Sleep(rm_val); }; var sw_out = new Stopwatch(); task.BeginInvoke(sw_out, (ar) => { task.EndInvoke(ar); mre.Set(); sw_out.Stop(); result.Success = true; result.Message = DateTime.Now + "->操作成功,耗时:" + sw_out.ElapsedMilliseconds.ToString()+"毫秒。"; }, null); if (!mre.WaitOne(1500)) { return result; } return result; }