void DispatchEvent(ST.WaitCallback eventCallback) { lock (eventQueue) { eventQueue.Add(eventCallback); ST.Monitor.PulseAll(eventQueue); } }
void EventDispatcher() { while (true) { ST.WaitCallback[] cbs; lock (eventQueue) { if (eventQueue.Count == 0) { ST.Monitor.Wait(eventQueue); } cbs = new ST.WaitCallback [eventQueue.Count]; eventQueue.CopyTo(cbs, 0); eventQueue.Clear(); } foreach (ST.WaitCallback wc in cbs) { try { wc(null); } catch (Exception ex) { Console.WriteLine(ex); } } } }
void AcceptHander(object ias) { var UpdateSocketListEventHandercback = new System.Threading.WaitCallback(UpdateSocketListEventHander); while (true) { Socket handler = socketLisener.Accept(); //连接到服务器的客户端Socket封装类 WeaveNetWorkItems netc = new WeaveNetWorkItems(); if (Certificate != null) { netc.Stream = Authenticate(handler, Certificate, SslProtocols.Default); netc.Stream.AuthenticateAsServer(Certificate, false, SslProtocols.Tls, true); } netc.SocketSession = handler; weaveNetworkItems.Add(netc); if (Setherd(netc, 1)) { System.Threading.ThreadPool.QueueUserWorkItem( UpdateSocketListEventHandercback, handler); } } }
public virtual void Start(int port) { acallsend = new AsyncCallback(SendDataEnd); ReceiveBitEventHandercback = new System.Threading.WaitCallback(ReceiveBitEventHander); ReceiveEventHandercback = new System.Threading.WaitCallback(ReceiveEventHander); Port = port; if (weaveDataType == WeaveDataTypeEnum.Json && waveReceiveEvent == null) { throw new Exception("没有注册receiveevent事件"); } if (weaveDataType == WeaveDataTypeEnum.Bytes && weaveReceiveBitEvent == null) { throw new Exception("没有注册receiveeventbit事件"); } if (weaveDataType == WeaveDataTypeEnum.custom && weaveReceiveBitEvent == null) { throw new Exception("没有注册receiveeventbit事件"); } socketLisener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, port); socketLisener.Bind(localEndPoint); socketLisener.Listen(1000000); System.Threading.ThreadPool.SetMaxThreads(100, 100); Thread ThreadAcceptHander = new Thread(new ParameterizedThreadStart(AcceptHander)); ThreadReceiveHander = new Thread(new ParameterizedThreadStart(ReceiveHander)); //Thread ThreadReceivePageHander = new Thread(new ParameterizedThreadStart(ReceivePageHander)); Thread ThreadKeepAliveHander = new Thread(new ParameterizedThreadStart(this.KeepAliveHander)); ThreadAcceptHander.Start(); ThreadReceiveHander.Start(); // ThreadReceivePageHander.Start(); ThreadKeepAliveHander.Start(); }
private static void EndFireAndForget(IAsyncResult ar) { System.Threading.WaitCallback callback = (System.Threading.WaitCallback)ar.AsyncState; try { callback.EndInvoke(ar); } catch (Exception ex) { m_log.Error("[UTIL]: Asynchronous method threw an exception: " + ex.Message, ex); } ar.AsyncWaitHandle.Close(); }
public static void QueueUserWorkItem(System.Threading.WaitCallback callback, object state) { if (Pool != null) { QueueWorkItemFunc2.Invoke(Pool, new object[] { Delegate.CreateDelegate(WorkItemCallbackType, callback, Invoker.Method), state }); } else { System.Threading.ThreadPool.QueueUserWorkItem(sync => callback.Invoke(sync), state); } }
public static void QueueUserWorkItem(System.Threading.WaitCallback callback, object state) { if (Pool != null) { Pool.QueueWorkItem(sync => { callback.Invoke(sync); return(null); }, state); } else { System.Threading.ThreadPool.QueueUserWorkItem(sync => callback.Invoke(sync), state); } }
public HighPrecisionTimer(System.Threading.WaitCallback _callback, object _stateInfo, Int32 _dueTime, Int32 _period) { dueTime = _dueTime; period = _period; callback = _callback; stateInfo = _stateInfo; flag.Reset(); running = true; ThreadPool.QueueUserWorkItem(Spinner, stateInfo); }
internal void Post(SendOrPostCallback cb, object args) { if (m_synchronizeInvoke != null) { m_synchronizeInvoke.BeginInvoke(cb, args); } else { ThreadPool.QueueUserWorkItem(cb, args); } }
public QueedTask(System.Threading.WaitCallback callback, object state, int delay) { this.state = state; this.delay = delay; this.callback = callback; lock (WorldTasks.Tasks) { Trace.TraceInformation("Queed new task"); WorldTasks.Tasks.Add(this); } }
void QueueTask(ST.WaitCallback cb) { lock (debugger) { if (stoppedWorkQueue.Count > 0) { stoppedWorkQueue.Add(cb); } else { cb(null); } } }
static void Main(string[] args) { System.Threading.WaitCallback callBack; callBack = new System.Threading.WaitCallback(PooleFunc); //callBack = (state) => { }; Console.WriteLine("Main thread is pool thread: {0}, hashCode:{1}", Thread.CurrentThread.IsThreadPoolThread, Thread.CurrentThread.GetHashCode()); ThreadPool.QueueUserWorkItem(callBack, "Is there any screw left?"); ThreadPool.QueueUserWorkItem(callBack, "How much is a 40w bulb?"); ThreadPool.QueueUserWorkItem(callBack, "Decrease stock of monkey wrench"); Console.ReadKey(); }
static void Main(string[] args) { Console.WriteLine($"Main thread started. ThreadID: {TP.Thread.CurrentThread.ManagedThreadId}"); Printer p = new Printer(); TP.WaitCallback workItem = new TP.WaitCallback(PrintTheNumbers); for (int i = 0; i < 10; i++) { TP.ThreadPool.QueueUserWorkItem(workItem, p); } Console.WriteLine($"All tasks queued."); Console.ReadLine(); }
public void Send(string[] mailAddress) { if (mailAddress != null) { System.Threading.WaitCallback callBack = new System.Threading.WaitCallback(this.Send); for (int i = 0; i < mailAddress.Length; i++) { string text = mailAddress[i]; if (!string.IsNullOrEmpty(text)) { System.Threading.ThreadPool.QueueUserWorkItem(callBack, text.Trim()); } } } }
public static bool PushWork(System.Threading.WaitCallback workfunc, BaseMultThreadWorkData data) { if (m_bDisposedThread || null == workfunc) { return(false); } if (isSingleThread) { workfunc(data); return(true); } return(ThreadPool.QueueUserWorkItem(workfunc, data)); }
private void DoRemembered(bool authenticated, bool remembered, bool discoverableOnly, AsyncOperation asyncOp) { if ((authenticated || remembered) && !discoverableOnly) { var rmbd = m_cli.DiscoverDevices(255, authenticated, remembered, false, false); if (rmbd.Length != 0) { var e = new DiscoverDevicesEventArgs(rmbd, asyncOp.UserSuppliedState); SendOrPostCallback cb = delegate(object args) { OnDiscoveryProgress((DiscoverDevicesEventArgs)args); }; asyncOp.Post(cb, e); } } }
private void HandleDiscoNewDevice(InTheHand.Net.Bluetooth.Factory.IBluetoothDeviceInfo newDevice, object state) { Debug.WriteLine(DateTime.UtcNow.TimeOfDay.ToString() + ": HandleDiscoNewDevice."); AsyncOperation asyncOp = (AsyncOperation)state; Debug.Assert(newDevice != null); var rslt = new BluetoothDeviceInfo[] { new BluetoothDeviceInfo(newDevice) }; Debug.Assert(rslt.Length > 0, "NOT rslt.Length > 0"); var e = new DiscoverDevicesEventArgs(rslt, asyncOp.UserSuppliedState); SendOrPostCallback cb = delegate(object args) { OnDiscoveryProgress((DiscoverDevicesEventArgs)args); }; asyncOp.Post(cb, e); }
/// <summary> /// 开始多线程,统一处理异常 /// </summary> /// <param name="callback"></param> /// <param name="state"></param> /// <returns></returns> protected bool NewThread(System.Threading.WaitCallback callback) { try { return(System.Threading.ThreadPool.QueueUserWorkItem(callback)); } catch (Exception exp) { MessageBox.Show(this.baseFile + "\n" + exp.Message + "\n" + exp.StackTrace); } finally { this.CloseProcessBar(); } return(false); }
public static void Spawn(Character character, Match match) { uint model = uint.Parse(match.Groups[2].Value); byte b = byte.Parse(match.Groups[1].Value); int nb = Convert.ToInt16(match.Groups[3].Value); if (b == 0) { MapObject instance = null; System.Threading.WaitCallback callback = delegate(object state) { Singleton.Templates.UnspawnInstance(instance); }; //if (Singleton.Templates.SpawnNpcInstance(model, character.Position, character.Yaw, character.currentzone, false, out instance)) //{ //QueedTask timer = new QueedTask(callback, instance, 300000); //} if (nb > 0) { for (int i = 1; i <= nb; i++) { Singleton.Templates.SpawnNpcInstance(model, character.Position, character.Yaw, character.currentzone, false, out instance); } } } else if (b == 1) { MapObject instance; Point newPosition = character.Position; newPosition.x += (float)(200 * Math.Cos(character.Yaw.rotation * (Math.PI / 32768))); newPosition.y += (float)(200 * Math.Sin(character.Yaw.rotation * (Math.PI / 32768))); Singleton.Templates.SpawnItemInstance(model, newPosition, character.Yaw, character.currentzone, out instance); } else { CommonFunctions.Broadcast(character, character, "Invalid argument"); } }
public static bool Execute(System.Threading.WaitCallback callback, object state) { try { return System.Threading.ThreadPool.QueueUserWorkItem((data) => { try { callback(data); } catch (Exception ex) { // log the exception } }, state); } catch (Exception e) { // log the exception } return false; }
/// <summary> /// 启动线程 /// </summary> /// <param name="dataList">数据列表</param> /// <param name="iThreadDataItem">数据处理逻辑类</param> /// <param name="itemCallback">IThreadDataItem 执行完回调函数</param> /// <param name="callback">线程结束回调函数</param> /// <param name="initThreadCount">初始执行线程数量</param> public void Run(List <T> dataList, IThreadDataItem <T> iThreadDataItem, Action <T> itemCallback, Action <int> callback, int initThreadCount = 10) { this.callbackCount = 0; this.dataList = dataList; this.iThreadDataItem = iThreadDataItem; this.itemCallback = itemCallback; this.callback = callback; ThreadPool.SetMinThreads(1, 1); ThreadPool.SetMaxThreads(initThreadCount, initThreadCount); foreach (T t in dataList) { // 初始化线程帮助类,传递相关数据来执行线程逻辑 ThreadItemDataHelper <T> threadItemDataHelper = new ThreadItemDataHelper <T>(t, this.iThreadDataItem.NewItem(), this.ThreadCallback); // 使用线程池 System.Threading.WaitCallback waitCallback = new System.Threading.WaitCallback(threadItemDataHelper.Callback); System.Threading.ThreadPool.QueueUserWorkItem(waitCallback); } this.manualEvent.WaitOne(); this.manualEvent.Reset(); }
private void HandleDiscoComplete(IAsyncResult ar) { AsyncOperation asyncOp = (AsyncOperation)ar.AsyncState; DiscoverDevicesEventArgs e; try { #if PRE_V2_4 FuncDiscoDevs dlgt = Interlocked.Exchange(ref m_dlgt, null); BluetoothDeviceInfo[] arr = dlgt.EndInvoke(ar); #else BluetoothDeviceInfo[] arr = m_cli.EndDiscoverDevices(ar); #endif e = new DiscoverDevicesEventArgs(arr, asyncOp.UserSuppliedState); } catch (Exception ex) { e = new DiscoverDevicesEventArgs(ex, asyncOp.UserSuppliedState); // TO-DO ?? Set Cancelled if disposed? } // SendOrPostCallback cb = delegate(object args) { OnDiscoveryComplete((DiscoverDevicesEventArgs)args); }; asyncOp.PostOperationCompleted(cb, e); }
public static void QueueUserWorkItem( WaitCallback callBack // NOTE: we do not expose options that allow the callback to be queued as an APC ) { QueueUserWorkItem(callBack, null); }
private void StartWorkThreadProcess() { IList<GPSDataProcessor> processors = new List<GPSDataProcessor>(); GPSDataProcessor p; p = new Processor.CameraDataProcessor(camera); processors.Add(p); camera.Clear(); p = new Processor.HistoryDataProcessor(history); processors.Add(p); history.Clear(); p = new Processor.UnlessDataProcessor(unless); processors.Add(p); unless.Clear(); p = new Processor.FetachDataProcessor(fetach); processors.Add(p); fetach.Clear(); //<!--历史、图片、无效、补传数据处理方式,threadpool,createthread,currentthread--> //string type = System.Configuration.ConfigurationManager.AppSettings["gpsdataprocessType"]; switch (processtype) { case "currentthread": Process(processors); break; case "threadpool": System.Threading.WaitCallback callback = new System.Threading.WaitCallback(Process); System.Threading.ThreadPool.QueueUserWorkItem(callback, processors); break; case "createthread": System.Threading.Thread t = new Thread(new ParameterizedThreadStart(Process)); t.Start(processors); break; default: Process(processors); break; } }
static void CheckForUpdates(State state) { if (/*nochecknewversion &&*/ notracking) return; //DateTime now = DateTime.Now; //if (lastCheck == DateTime.MinValue || lastCheck + new TimeSpan (0, 15, 0) < now) { // lastCheck = now; System.Threading.Interlocked.Increment (ref updatesBusy); manualResetEvent.Reset (); System.Threading.WaitCallback waitCallback = new System.Threading.WaitCallback (delegate(object state2) { CheckForUpdatesAsync (state); } ); System.Threading.ThreadPool.QueueUserWorkItem (waitCallback); }
public void FireAndForget(System.Threading.WaitCallback callback, object obj) { callback.BeginInvoke(obj, EndFireAndForget, callback); }
public void FireAndForget(System.Threading.WaitCallback callback) { callback.BeginInvoke(null, EndFireAndForget, callback); }
internal QueueUserWorkItemCallbackDefaultContext(WaitCallback waitCallback, Object stateObj) { callback = waitCallback; state = stateObj; }
internal WorkItem(WaitCallback callback, object state) { Contract.Requires(callback != null); this.callback = callback; this.state = state; }
/// <summary> /// Run the callback via a threadpool thread. /// </summary> /// <remarks> /// Such jobs may run after some delay but must always complete. /// </remarks> /// <param name="callback"></param> /// <param name="obj"></param> /// <param name="name">The name of the job. This is used in monitoring and debugging.</param> public static void RunInThreadPool(System.Threading.WaitCallback callback, object obj, string name, bool timeout = true) { Util.FireAndForget(callback, obj, name, timeout); }
void EventDispatcher () { while (true) { ST.WaitCallback[] cbs; lock (eventQueue) { if (eventQueue.Count == 0) ST.Monitor.Wait (eventQueue); cbs = new ST.WaitCallback [eventQueue.Count]; eventQueue.CopyTo (cbs, 0); eventQueue.Clear (); } foreach (ST.WaitCallback wc in cbs) { try { wc (null); } catch (Exception ex) { Console.WriteLine (ex); } } } }
public static void exec2(System.Threading.WaitCallback fn, object x) { ThreadPool.QueueUserWorkItem(fn, x); }
internal QueueUserWorkItemCallback(WaitCallback waitCallback, Object stateObj, ExecutionContext ec) { callback = waitCallback; state = stateObj; context = ec; }