/// <summary> /// Runs the specified method on the engine thread, and returns its result as an /// <c>object</c>. Blocks until the method has been executed. /// </summary> /// <param name="method">Method to execute</param> /// <returns>Result of the method</returns> protected virtual object RunOnThread(Func <IJsEngine, object> method) { var item = new ThreadWorkItem { Method = method, WaitForCompletion = new ManualResetEvent(initialState: false), }; _queue.Add(item); item.WaitForCompletion.WaitOne(); if (item.Exception != null) { throw item.Exception; } return(item.Result); }
static void fun1() { ThreadWorkItem itemMain = new ThreadWorkItem { //线程0,1持续运行,设置true后非阻塞,持续运行。需要手动触发Reset()才会阻塞实例所在当前线程 ManualResetEvent = new ManualResetEvent(true), }; //线程工作集合 Task.Factory.StartNew(() => { Thread t = null; ThreadWorkItem item = null; for (int i = 0; i < 2; i++) { t = new Thread((o) => { var w = o as ThreadWorkItem; if (w == null) { return; } while (true) { //阻塞当前线程 bool t = w.ManualResetEvent.WaitOne(10000); Console.WriteLine("我是线程:" + Thread.CurrentThread.Name + ":群里无聊吗?" + !t); if (!t) { break; } Thread.Sleep(200); } Console.WriteLine("我是线程:" + Thread.CurrentThread.Name + "退出了群聊"); }); t.Name = "Hello,i 'am Thread: " + i; item = new ThreadWorkItem { //线程0,1持续运行,设置true后非阻塞,持续运行。需要手动触发Reset()才会阻塞实例所在当前线程 ManualResetEvent = new ManualResetEvent(true), Thread = t, ThreadManagerId = t.ManagedThreadId, ThreadName = t.Name }; Works.Add(item); t.Start(item); } //5秒后准备暂停一个线程1。线程0持续运行 Thread.Sleep(1000); Console.WriteLine("close..."); Works[1].ManualResetEvent.Reset(); //5秒后恢复线程1;线程0,1持续运行 Thread.Sleep(1000); Console.WriteLine("open..."); Works[1].ManualResetEvent.Set(); //5秒后准备暂停一个线程0。线程1持续运行 Thread.Sleep(1000); Console.WriteLine("close0..."); Works[0].ManualResetEvent.Reset(); //5秒后恢复线程1;线程0,1持续运行 Thread.Sleep(1000); Console.WriteLine("open0..."); Works[0].ManualResetEvent.Set(); //5秒后恢复线程1;线程0,1持续运行 Thread.Sleep(5000); Console.WriteLine("closeAll..."); Works[0].ManualResetEvent.Reset(); Works[1].ManualResetEvent.Reset(); while (true) { ThreadState ts = Thread.CurrentThread.ThreadState; Console.WriteLine("我是线程:" + Thread.CurrentThread.Name + "群主解散了群聊"); //while (true) //{ // Thread.CurrentThread.TrySetApartmentState(System.Threading.ThreadState.WaitSleepJoin); // } Thread.CurrentThread.Interrupt(); itemMain.ManualResetEvent.WaitOne(); Thread.Sleep(2000); //Reset(); } }); /// <summary> /// 假设的网络请求 /// </summary> /// <param name="state">参数</param> }