public IEnumerator Load() { //return if already loading while (loading) { yield return(new WaitForSeconds(0)); } //callback if already loaded. if (loaded) { yield break; } //set as loading loading = true; LoadCount++; LoadingScreen = LoadingScreen ?? App.Resource.Prefab.LoadingCanvas(); //check if we need to load the dependencies. bool dependencies_loaded = true; foreach (var dependency in dependencyList) { if (!dependency.loaded) { dependencies_loaded = false; break; } } //if no dependencies needed, just build yourself directly if (dependencies_loaded) { yield return(Build()); Loaded(); yield break; } //otherwise define per-dependency-built callback int dependency_needed_count = dependencyList.Count; //and load all dependencies, then trigger self build foreach (var dependency in dependencyList) { yield return(dependency.Load()); Interlocked.Decrement(ref dependency_needed_count); //when all requests have been processed, call async callback's if (Interlocked.Equals(dependency_needed_count, 0)) { yield return(Build()); Loaded(); yield break; } } }
private void UpdateStopStatus() { bool AllEndSignal = !Interlocked.Equals(ThreadBox.IsStop, 0); StopStatus = (!Interlocked.Equals(ThreadBox.IsStop, 0) && !(!job.canStop && job.isStop)) || tStop; }
/// <summary> /// This event could be raised from multiple threads. Only perform thread-safe operations /// </summary> private void PackageRestoreManager_PackageRestored(object sender, PackageRestoredEventArgs args) { PackageIdentity packageIdentity = args.Package; if (args.Restored && CancellationTokenSource != null && !CancellationTokenSource.IsCancellationRequested) { bool canceled = false; Interlocked.Increment(ref CurrentCount); // The rate at which the packages are restored is much higher than the rate at which a wait dialog can be updated // And, this event is raised by multiple threads // So, only try to update the wait dialog if an update is not already in progress. Use the int 'WaitDialogUpdateGate' for this purpose // Always, set it to 1 below and gets its old value. If the old value is 0, go and update, otherwise, bail if (Interlocked.Equals(Interlocked.Exchange(ref WaitDialogUpdateGate, 1), 0)) { _waitDialog.UpdateProgress( String.Format(CultureInfo.CurrentCulture, Resources.RestoredPackage, packageIdentity.ToString()), String.Empty, szStatusBarText: null, iCurrentStep: CurrentCount, iTotalSteps: TotalCount, fDisableCancel: false, pfCanceled: out canceled); Interlocked.Exchange(ref WaitDialogUpdateGate, 0); } } }
public void Wait() { do { Thread.Sleep(1); } while (Interlocked.Equals(bIsShown, true)); }
/// <summary> /// 日志输出 /// </summary> /// <param name="sender"></param> private static void WriteLog(object sender) { while (true) { List <LogInfo> infos = new List <LogInfo>(); LogInfo log; while (readInfo.TryDequeue(out log)) { LogInfo info = log; infos.Add(info); } LogInfo[][] writeInfos = infos.Split(200); foreach (LogInfo[] item in writeInfos) { WriteLogToLocal(item); if (Action.Output.IsOpenConsole) { WriteLogToConsole(item); } } Thread.Sleep(100); if (Interlocked.Equals(writeInfo, logInfo1)) { Interlocked.Exchange <ConcurrentQueue <LogInfo> >(ref writeInfo, logInfo2); Interlocked.Exchange <ConcurrentQueue <LogInfo> >(ref readInfo, logInfo1); } else { Interlocked.Exchange <ConcurrentQueue <LogInfo> >(ref writeInfo, logInfo1); Interlocked.Exchange <ConcurrentQueue <LogInfo> >(ref readInfo, logInfo2); } } }
public static void Lock() { while (Interlocked.Equals(_mutexState, 1)) { } Interlocked.Exchange(ref _mutexState, 1); }
public new T Dequeue() { T item = default(T); int count; if (Stop) { m_parent.Debug("Dequeueing null item after stop"); return(item); } while (Interlocked.Equals(m_count, 0)) { m_parent.Debug("Queue empty - entering wait state"); m_go.WaitOne(); if (Stop) { m_parent.Debug("Exited wait state - dequeueing null item after stop"); return(item); } } lock (m_lock) { count = Interlocked.Decrement(ref m_count); item = base.Dequeue(); } Debug("Dequeued item", count, item); return(item); }
public void read() { lock (this) { if (w_wcount != 0) { waitQueue.Add("ReadThread:" + Thread.CurrentThread.ManagedThreadId); printWaitThread(); while (!Interlocked.Equals(w_wcount, 0)) { Monitor.Pulse(this); Monitor.Wait(this); } } //2.no writer and no waiting writer rcount++; Console.WriteLine("{2}\tThread:{0} is Reading...\t\treader:{1}", Thread.CurrentThread.ManagedThreadId, rcount, DateTime.Now.ToString("yy-MM-dd hh:mm:ss.fffffff")); if (waitQueue.Contains("ReadThread:" + Thread.CurrentThread.ManagedThreadId)) { waitQueue.Remove("ReadThread:" + Thread.CurrentThread.ManagedThreadId); } printWaitThread(); Monitor.Pulse(this); Monitor.Wait(this); Thread.Sleep(1000); Interlocked.Decrement(ref rcount); Console.WriteLine("{2}\tThread:{0} finished Reading...\treader:{1}", Thread.CurrentThread.ManagedThreadId, rcount, DateTime.Now.ToString("yy-MM-dd hh:mm:ss.fffffff")); Monitor.Pulse(this); } }
private void Initialize(Configuration configuration) { if (Interlocked.Equals(this.Stopped, 1)) { return; } this.OnRejected = configuration.OnRejected; this.Thread = new Thread(() => { while (true) { try { Action action = null; InternalExceptionHandler.Rethrow(InternalExceptionCode.ActionQueueTryTake, () => this.Queue.TryTake(out action)); if (action == AbortCommand) { return; } action?.Invoke(); } catch (Exception exception) { configuration.ExceptionHandler?.Invoke(exception); } } }); this.Thread.Priority = configuration.Priority; this.Thread.Start(); }
private static void GUIWaitCursorThread() { //start animation only if _showCount equals 1 //this is to prevent animation starting from beginning every time Show() is called, making it "jumpy" if (Interlocked.Equals(_showCount, 1)) { _animation.Begin(); } }
/// <summary> /// Add <see cref="QueueItem"/> to the queue list. /// </summary> /// <param name="item">QueueItem to be processed</param> public void Add(QueueItem item) { Log.Debug("Queue.Add: " + item.Guid.ToString()); Items.Enqueue(item); if (Interlocked.Equals(running, 0)) //!running { Log.Debug("Queue.Add: Timer restarted"); Interlocked.Exchange(ref running, 1); timer.Change(1, milliseconds); } }
private void TaskCompleted() { ProgressPosition--; if (Interlocked.Equals(TasksCounter, 0)) { ProgressPosition = 0; EnDsCommands(CommandSet.csScan); ProgressStatus = "Completed " + ProgressMax; } }
protected virtual void OnPropertyChanged(string PropertyName) { if (!Interlocked.Equals(suspendPropChangeCalls, 0)) { return; } this.ModifiedDate = DateTime.Now; if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(PropertyName)); } }
internal void Run(Action callback) { if (Interlocked.Equals(this.Stopped, 1)) { if (callback == AbortCommand) { return; } this.OnRejected?.Invoke(); return; } this.Queue.Add(callback); }
private void OnConnectedHandler() { lock (m_connectOMCLocker) { if (Interlocked.Equals(m_isOMCAvailable, 0L)) { SetOMCAvailable(); SQLUtil.UpdateSvrStatus(m_Connstr, "1", "服务器连接成功!", m_SvrID.ToString()); ClearNMAlarm(omcName, Constants.MO_SOURCEOMC, Constants.TKALM_OMCALM, DateTime.Now); SQLUtil.ClearOMCAlarm(m_Connstr, m_omc.Omc); } } }
//error login handler //broken connection handler /// <summary> /// msg生成告警用 /// </summary> /// <param name="msg"></param> private void OnNetInterruptHandler(string msg) { lock (m_connectOMCLocker) { if (Interlocked.Equals(m_isOMCAvailable, 1L) && CheckAllThreadNet()) { SetOMCUnavailable(); SQLUtil.UpdateSvrStatus(m_Connstr, "0", "服务器连接断开!", m_SvrID.ToString()); RaiseOmcAlarm(msg); } } }
private void CommitToCatalog() { // When the CatalogWriterGate is 0, the catalog is open for writing. If 1, it is closed for writing // Using Interlocked.Exchange, set value to 1 and close the gate, and check if the value returned is 0 to see if the gate was open // If the value returned is 1, that is, if the gate was already closed, do nothing // When 2 or more threads reach this point, while the gate is open, only 1 thread will enter. Rest will find that the gate is already closed and leave if (Interlocked.Equals(Interlocked.Exchange(ref CatalogWriterGate, 1), 0)) { try { using (AppendOnlyCatalogWriter writer = new AppendOnlyCatalogWriter(CatalogStorage, new CatalogContext(), CatalogPageSize)) { ConcurrentQueue <JToken> headStatsQueue; while (StatsQueueOfQueues.TryDequeue(out headStatsQueue)) { if (headStatsQueue.Count == 0) { // An emtpy StatsQueue, ignore this one and go to the next one continue; } JArray statsCatalogItem = new JArray(); foreach (JToken packageStats in headStatsQueue) { statsCatalogItem.Add(packageStats); } // Note that at this point, DateTime is already in UTC string minDownloadTimestampString = statsCatalogItem[0][CatalogDownloadTimestamp].ToString(); DateTime minDownloadTimestamp = DateTime.Parse(minDownloadTimestampString, null, System.Globalization.DateTimeStyles.RoundtripKind); string maxDownloadTimestampString = statsCatalogItem[statsCatalogItem.Count - 1][CatalogDownloadTimestamp].ToString(); DateTime maxDownloadTimestamp = DateTime.Parse(minDownloadTimestampString, null, System.Globalization.DateTimeStyles.RoundtripKind); writer.Add(new StatisticsCatalogItem(statsCatalogItem, minDownloadTimestamp, maxDownloadTimestamp)); writer.Commit().Wait(); } } } catch (Exception ex) { Trace.TraceError(ex.ToString()); } Interlocked.Exchange(ref CatalogWriterGate, 0); } else { Trace.WriteLine("Another thread is committing to catalog. Skipping"); } }
/// <summary> /// Service entry point. /// </summary> public void ServiceMain() { this.openTasks = 0; this.started = false; this.serverInit.Reset(); Socket serverSocket = null; try { try { serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); serverSocket.Bind(new IPEndPoint(IPAddress.Any, this.applicationSettings.ServerPort)); serverSocket.Listen(10); this.started = true; if (this.interactiveMode) { Console.WriteLine("Service is running"); } } finally { this.serverInit.Set(); } WaitHandle[] events = new WaitHandle[] { this.acceptCompleted, this.stopServiceEvent }; for (;;) { this.acceptCompleted.Reset(); IAsyncResult ar = serverSocket.BeginAccept(AcceptCallback, serverSocket); if (WaitHandle.WaitAny(events) == 1) { while (!Interlocked.Equals(this.openTasks, 0)) { this.endRequestEvent.WaitOne(); } break; } } } catch (Exception error) { this.ReportNestedError(error); } finally { if (serverSocket != null) { serverSocket.Close(); } } }
private void StartDownload() { //check if the downloads has been canceled, items have been finished or if (CANCEL || queue.Count == 0 || Interlocked.Equals(processed, totalCount)) { if (CANCEL) { OnLog("Download canceled."); } else { OnLog("Finished download."); } return; } lock (lockObj) { //check if any file remains for (int i = 0; !Interlocked.Equals(processesing, maxThreads) && (queue.Count > 0) && !CANCEL; i++) { //get next item var file = queue.Dequeue(); try { //skip existing files. Remove this to overwrite if (!File.Exists(file.Path)) { //start downloading the file var cli = new WebClient(); OnDebug(string.Format("Downloading {0} to {1}", file.Address, file.Path)); cli.DownloadFileCompleted += cli_DownloadFileCompleted; Interlocked.Increment(ref processesing); cli.DownloadFileAsync(file.Address, file.Path); } else { OnDebug("Skipping file " + file.Path); } } catch (Exception) { OnLog("Error downloading file from " + file.Address); //Do whatever you want. Maybe write a debug message, stop download, etc. } } } }
/// <summary> /// 从数据库中取工单,有两个DoWork,一个取工单,一个处理工单 /// </summary> private void DoWork() { string msg = string.Empty; try { if (Interlocked.Equals(m_isOMCAvailable, 0L)) { CheckNetDelayTask(); } GetActiveTask();//获取任务-从数据库查询 } catch (Exception ex) { SendLog(ex.ToString()); } }
public void write() { lock (this) { if (rcount != 0) { waitQueue.Add("WriteThread:" + Thread.CurrentThread.ManagedThreadId); w_wcount++; while (!Interlocked.Equals(rcount, 0)) { Monitor.Pulse(this); Monitor.Wait(this); } } if (wcount != 0) { w_wcount++; if (!waitQueue.Contains("WriteThread:" + Thread.CurrentThread.ManagedThreadId)) { waitQueue.Add("WriteThread:" + Thread.CurrentThread.ManagedThreadId); } while (!Interlocked.Equals(wcount, 0)) { Monitor.Pulse(this); Monitor.Wait(this); } } wcount++; if (w_wcount != 0) { w_wcount--; } Console.WriteLine("{2}\tThread:{0} is Writing...\t\twriter:{1}", Thread.CurrentThread.ManagedThreadId, wcount, DateTime.Now.ToString("yy-MM-dd hh:mm:ss.fffffff")); if (waitQueue.Contains("WriteThread:" + Thread.CurrentThread.ManagedThreadId)) { waitQueue.Remove("WriteThread:" + Thread.CurrentThread.ManagedThreadId); } printWaitThread(); Thread.Sleep(1000); Interlocked.Decrement(ref wcount); Console.WriteLine("{2}\tThread:{0} finished Writing...\twriter:{1}", Thread.CurrentThread.ManagedThreadId, wcount, DateTime.Now.ToString("yy-MM-dd hh:mm:ss.fffffff")); Monitor.Pulse(this); } }
private void threadCreateWav() { int synindex = Interlocked.Increment(ref soundSynIndex) - 1; //int index= int.Parse(p[1]); while (synindex < soundFinishState.Length) { string filename = string.Format(@"{0}tmp_{1}.wav", bufferpath, synindex); int[] tmp = showSound(soundSentnece[synindex]); try { writeWAV(tmp, filename); } catch { } soundFinishState[synindex] = true; //用于启动朗读 if (Interlocked.Equals(isReading, -1)) { Interlocked.Exchange(ref isReading, synindex); if (Interlocked.Equals(isReading, synindex)) { while (soundPlayIndex < soundFinishState.Length && soundFinishState[soundPlayIndex]) { int readIndex = Interlocked.Increment(ref soundPlayIndex) - 1; if (!isRuning || readIndex >= soundFinishState.Length) { break; } string playfilename = string.Format(@"{0}tmp_{1}.wav", bufferpath, readIndex); //int[] tmp = myssc.showSound(sentences[i], this.print); if (File.Exists(playfilename)) { playSound(playfilename); File.Delete(playfilename); } } isReading = -1; } } synindex = Interlocked.Increment(ref soundSynIndex) - 1; } }
private void ThreadRun() { Interlocked.Exchange(ref mStop, 0); while (!Interlocked.Equals(mStop, 1)) { //config Write Options Program.ReaderXP.Options.TagWriteEPC.accessPassword = 0x0; //Assume all tag with no access password Program.ReaderXP.Options.TagWriteEPC.count = 6; //Assume 96bit epc only Program.ReaderXP.Options.TagWriteEPC.offset = 0; //Assume offset start from zero Program.ReaderXP.Options.TagWriteEPC.epc = new S_EPC(GetEPC()); /*Program.ReaderXP.Options.TagReadEPC.accessPassword = 0x0; * Program.ReaderXP.Options.TagReadEPC.count = 6; * Program.ReaderXP.Options.TagReadEPC.offset = 0; * Program.ReaderXP.Options.TagReadEPC.retryCount = 7;*/ Program.ReaderXP.StartOperation(Operation.TAG_WRITE_EPC, true); } TriggerButton(); }
private static void ConnectionCheckerTask() { var isConnected = IsConnectedToInterner(); if (!isConnected) { Interlocked.Increment(ref _errorCount); Console.WriteLine("**** Fails #{0} in connection checker *****", _errorCount); if (Interlocked.Equals(_errorCount, ErrourCountLimit)) { Console.WriteLine("******************** Disconnection noticed *************************************"); IsConnected = false; HandleDisconnection(); } } else { Interlocked.Exchange(ref _errorCount, 0); } }
/// <summary> /// Takes a QueueItem to be processed and then processes it. /// If there are no more QueueItems then the Timer can be suspended. /// </summary> /// <param name="stateInfo"></param> public void Process(Object stateInfo) { Log.Debug("Queue.Process"); Log.Debug("Queue.Process: Count: " + Items.Count.ToString()); QueueItem itemToProcess; if (Items.TryDequeue(out itemToProcess)) { ProcessItem(itemToProcess); } else { if (Interlocked.Equals(running, 1)) { Log.Debug("Queue.Process: Suspending Timer."); Interlocked.Exchange(ref running, 0); //running = false; timer.Change(Timeout.Infinite, Timeout.Infinite); } } }
private void DispatchTask() { Task currentTask; while (m_tasks.Count > 0 && Interlocked.Read(ref m_PendingRun) == 1 && Interlocked.Equals(m_isOMCAvailable, 1L)) { int index = WaitHandle.WaitAny(m_idleHandles); lock (m_tasks) { currentTask = m_tasks.Dequeue(); if (CheckAlreadyWork(currentTask.TaskID, currentTask.OnuID)) { m_tasks.Enqueue(currentTask); continue; } } SendLog(string.Format("Thread {0} get task {1}", index.ToString(), currentTask.TaskID)); m_tl1Clients[index].SetTask(currentTask); } }
private void ThreadStart() { this.Status = Status.BUSY; startedThread.Set(); while (!Interlocked.Equals(stopFlag, 1)) { if (synchQ.Count > 0) { string data = synchQ.Dequeue() as string; SQLiteErrorCode result = Add(data); if (OnCheckDataExist != null) { OnCheckDataExist(this, new CheckDataExistEventArgs(data, result == SQLiteErrorCode.Constraint)); } } else { Thread.Sleep(1); } } Interlocked.Exchange(ref stopped, 1); this.Status = Status.IDLE; }
public void Async(List <HTTPRequest> request_list, OnAppRespondedDelegate callback) { JSONNode cumulatedResponses = new JSONArray(); int request_pending_count = request_list.Count; foreach (var request in request_list) { var oldCallback = request.Callback; request.Callback = (HTTPRequest request_, HTTPResponse response_) => { //call original callback oldCallback(request_, response_); //write errors if any. if (request_.State != HTTPRequestStates.Finished) { cumulatedResponses.Add(request_.Uri.ToString() + ": didn't terminate properly"); } var json = JSON.Parse(request_.Response.DataAsText); if (!(json != null && json["error"] == json["null"])) { cumulatedResponses.Add(request_.Uri.ToString() + ": error"); } //decrement counter Interlocked.Decrement(ref request_pending_count); //when all requests have been processed, call async callback's if (Interlocked.Equals(request_pending_count, 0)) { callback(cumulatedResponses); } }; request.Send(); } }
private void DispatchOltOfflineTask() { Task currentTask; int i = m_oltOfflineTasks.Count; for (; i > 0; i--) { if (Interlocked.Read(ref m_PendingRun) == 1 && Interlocked.Equals(m_isOMCAvailable, 1L)) { int index = WaitHandle.WaitAny(m_idleHandles); lock (m_oltOfflineTasks) { currentTask = m_oltOfflineTasks.Dequeue(); } SendLog(string.Format("Thread {0} get oltoffline task {1}", index.ToString(), currentTask.TaskID)); m_tl1Clients[index].SetTask(currentTask); } else { break; } } }
/// <summary> /// 检测线程是否关闭 true是关闭 /// </summary> /// <returns></returns> public static bool CheckThreadStop() { return(!Interlocked.Equals(IsStop, 0)); }