private void UpdateInterface() { while (true) { DispatcherOperation op = Dispatcher.BeginInvoke(new Action(delegate() { DateTime now = DateTime.Now; TimeSpan elapsed = now - start; TimeSpan remaining = end - now; TimeSpan total = end - start; if (remaining.Ticks <= 0) { TimerExpired(); } else { UpdateTitles(ToString(remaining)); UpdateProgress(elapsed, total); } } )); op.Wait(); Thread.Sleep(1000); } }
protected object getPropertyDispatcher(object from_me, String get_me) { DispatcherOperation dispatcho = this.Dispatcher.BeginInvoke(new getPropertyDelegate(this.getProperty), from_me, get_me); dispatcho.Wait(); return(dispatcho.Result); }
private void ListBoxItem_PreviewMouseDown(object sender, MouseButtonEventArgs e) { ListBoxItem item = sender as ListBoxItem; if (e.ClickCount == 1 && item.IsSelected) { if (OAMScanInformationClosingPopup.IsOpen) { closeScanInformation(); } else { _openPopupOnMouseUp = true; } } else if (e.ClickCount == 2) { _blockDoDragDrop = true; DispatcherOperation result = Dispatcher.BeginInvoke(new Action(() => { closeScanInformation(); OnSnapshotDoubleClick(); })); result.Wait(); Thread.Sleep(200); _blockDoDragDrop = false; } }
/// <summary> /// 创建实例集合视图 /// </summary> protected override void BuildContentsView() { base.BuildContentsView(); DispatcherOperation operation = DHelper.InvokeOnMain(() => TreeView = Contents.Where(t => t.IsFirstLevel).AsICV()); operation.Wait(); }
public void RunReader() { IKernelLink readerLink = KernelLinkProvider.ReaderLink; while (keepRunning) { // we only wait if there is already something on the link. if (readerLink.Ready) { //stopWatch.Reset(); //stopWatch.Start(); //while (stopWatch.ElapsedMilliseconds <= loopMillis) //{ // if (readerLink.Ready) // { try { DebugPrint("Packet arriving on Reader link"); PacketType pkt = readerLink.NextPacket(); var readerDelegate = new ReaderMethodCaller(readerLink.HandlePacket); DebugPrint("calling BeginInvoke"); DispatcherOperation op = dispatcher.BeginInvoke(readerDelegate, new object[] { pkt }); DebugPrint("calling Wait()"); op.Wait(); // also has a millis arg DebugPrint("back from Wait()"); readerLink.NewPacket(); DebugPrint("Finished handling packet on Reader link"); // if we got a packet, we reset the watch //stopWatch.Reset(); //stopWatch.Start(); } catch (MathLinkException e) { // 11 is "other side closed link"; not sure why this succeeds clearError, but it does. if (e.ErrCode == 11 || !readerLink.ClearError()) { DebugPrint("Exception on Wolfram Reader link: " + e); KernelLinkProvider.CloseLinks(); keepRunning = false; } else { readerLink.NewPacket(); } } // } // else if (sleepMillis >= 0) // { // System.Threading.Thread.Sleep(sleepMillis); // } // } } else { System.Threading.Thread.Sleep(1); } } isReaderThreadRunning = false; }
public void Wait(TimeSpan timeout) { if (executeTask == null || !IsExecuting) { return; } executeTask.Wait(timeout); completeTaskOperation?.Wait(timeout); }
public override void Perform() { if (IsWaitForever) { DispatcherOperation.Wait(); } else { DispatcherOperation.Wait(TimeSpan); } }
private void Execute() { try { while (!isDisposed) { Action action = actions.Take(cancellationTokenSource.Token); if (action != null) { DispatcherOperation operation = dispatcher.BeginInvoke(new Action(() => { try { if (!isDisposed) { action(); } } catch (COMException) { actions.Add(action); waitExcelBusy = true; } catch (Exception ex) { string message = $"'ExcelPostAsynchronousManager.ExecuteAction' failed.{ex.Message}"; Logger.Instance.LogException(LogType.Error, ex, message); } })); operation.Wait(); if (waitExcelBusy) { Thread.Sleep(50); waitExcelBusy = false; } } } } catch (Exception ex) { if (ex is OperationCanceledException) { Logger.Instance.Log(LogType.Info, "PostAsynchronousManager properly ended"); } else { Logger.Instance.LogException(LogType.Error, ex, $"PostAsynchronousManager not properly ended:{ex.Message}"); } } finally { actions.Dispose(); } }
public bool CanProcessCommandLineArgs(string[] args) { DispatcherOperation dispatcherOperation = UIThreadDispatcher.Instance.BeginInvoke <string[], bool>(DispatcherPriority.Input, new Func <string[], bool>(this.HandleCanProcessCommandLineArgs), args); int num = (int)dispatcherOperation.Wait(this.defaultWait); if (dispatcherOperation.Status != DispatcherOperationStatus.Completed) { return(false); } return((bool)dispatcherOperation.Result); }
/// <summary> /// Executes the specified delegate synchronously on the thread the Dispatcher is associated with. /// </summary> public void Invoke(Delegate d, object args) { if (CheckAccess()) { DispatcherOperation.Invoke(d, args); } else { DispatcherOperation operation = AddOperation(d, args, new AutoResetEvent(false)); operation.Wait(); } }
private void OnGetContext(HttpListenerContext context, Exception error) { if (!_dispatcher.CheckAccess()) { DispatcherOperation op = _dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => OnGetContext(context, error))); Thread.Sleep(100); op.Wait(); return; } UrlDetails url = new UrlDetails(context.Request.RawUrl); }
// Waits for a DispatcherOperation to complete. // Stops waiting if the proxy is done (disposed or error). private bool _WaitForOperation(DispatcherOperation op) { while (DispatcherOperationStatus.Completed != op.Wait(TimeSpan.FromMilliseconds(500))) { if (this.IsControllerProxyDone) { return(false); } } return(true); }
private void AddOperation(DispatcherPriority priority, Delegate d, object args, AutoResetEvent wait = null) { if (priority == DispatcherPriority.Invalid || priority == DispatcherPriority.Inactive) { throw new ArgumentException("Invalid Priority"); } if (d == null) { throw new ArgumentNullException("Null method"); } if (priority == DispatcherPriority.Send && CheckAccess()) { // Fast path: invoking at Send priority DispatcherOperation.Invoke(d, args, _context); } else { // Slow path: going through the queue DispatcherOperation operation = new DispatcherOperation { Priority = priority, Callback = d, Args = args, WaitEvent = wait }; lock (_operations) { _operations.Enqueue(operation); } if (wait != null) { if (CheckAccess()) { // We cannot lock this thread, so process the queue now ProcessQueue(); } else { // Block this thread and wait for the operation to get finished operation.Wait(); } } } }
private void UpdateTextThread(string message) { ThreadStart start = delegate() { DispatcherOperation operation = Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action <string>(UpdateText), message); DispatcherOperationStatus status = operation.Status; while (status != DispatcherOperationStatus.Completed) { status = operation.Wait(TimeSpan.FromMilliseconds(100)); } }; new Thread(start).Start(); }
public object EndInvoke(IAsyncResult result) { DispatcherAsyncResult asyncResult = result as DispatcherAsyncResult; if (asyncResult != null) { DispatcherOperation dispatcherOperation = asyncResult.AsyncState as DispatcherOperation; if (dispatcherOperation != null) { return(dispatcherOperation.Wait()); } } return(null); }
private void ExecuteActions() { try { foreach (Action action in actions) { if (action != null) { tryAgain = true; while (tryAgain) { DispatcherOperation operation = dispatcher.BeginInvoke(new Action(() => { try { action(); } catch (COMException) { waitExcelBusy = true; } catch (Exception ex) { string message = $"'ExcelPostAsynchronousManager.ExecuteAction' failed.{ex.Message}"; Logger.Instance.LogException(LogType.Error, ex, message); } })); operation.Wait(); if (waitExcelBusy) { Thread.Sleep(50); waitExcelBusy = false; tryAgain = true; } else { tryAgain = false; } } } } ExecutePostExecutionAction(); } finally { } }
/// <summary> /// 关闭窗口 /// </summary> /// <param name="dlg"></param> protected void TryCloseDlg(Window dlg) { if (dlg == null) { return; } DispatcherOperation operation = DHelper.InvokeOnMain(() => { if (dlg.IsVisible) { dlg.Close(); } }); operation.Wait(); }
protected void doUpdateThread() { while (State != UpdateFilterState.Terminate) { Thread.Sleep(10); Thread.SpinWait(1); switch (State) { case UpdateFilterState.Idle: break; case UpdateFilterState.UpdateInProgress: break; case UpdateFilterState.UpdateRequestQueued: break; case UpdateFilterState.UpdateRequested: lock (stateLock) { State = UpdateFilterState.UpdateInProgress; } Task.Run(() => { try { DispatcherOperation op = dispatcher.InvokeAsync(OnUpdate); op.Wait(); } finally { switch (State) { case UpdateFilterState.UpdateInProgress: State = UpdateFilterState.Idle; break; case UpdateFilterState.UpdateRequestQueued: State = UpdateFilterState.UpdateRequested; break; } } }); break; } } }
private void MonitorDispatcherOperation(DispatcherOperation operation) { while (operation.Wait(_uiEternity) != DispatcherOperationStatus.Completed) { // Threads get delayed when debugging, ignore this if it happens in the debugger. if (!Debugger.IsAttached) { var stack = new StackTrace(); _logger.Log( LogLevel.Warning, string.Format( "Dispatcher deadlock suspected. Operation status: {0} at: {1}", operation.Status, stack)); } } }
private void ShowLog(List <ShowLogItem> items) { try { if (items == null || items.Count == 0) { return; } DispatcherOperation dispatcherOperation = this.Dispatcher.BeginInvoke(this._priority, this._primitiveShowLogDelegate, items); dispatcherOperation.Wait(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } }
/// <summary> /// Runs <paramref name="action"/> on <paramref name="dispatcher"/>, eventually after <paramref name="delay"/>. /// Parameter <paramref name="priority"/> sets action priority. /// </summary> /// <param name="dispatcher">Dispatcher to use.</param> /// <param name="action">Action to run.</param> /// <param name="delay">Delay, before executing <paramref name="action"/>.</param> /// <param name="priority">Opeartion priority.</param> public static void Run(Dispatcher dispatcher, Action action, int delay = 0, DispatcherPriority priority = DispatcherPriority.Normal) { ThreadStart start = delegate() { if (delay >= 0) { Thread.Sleep(delay); } DispatcherOperation op = dispatcher.BeginInvoke(priority, action); DispatcherOperationStatus status = op.Status; while (status != DispatcherOperationStatus.Completed) { status = op.Wait(TimeSpan.FromMilliseconds(intervalCheckDelay)); } }; new Thread(start).Start(); }
/// <summary> /// 显示进程窗口 /// </summary> /// <returns></returns> protected Window ShowDlgProgress() { if (IsShowAsyncDlg) { return(null); } Window dlg = default; TokenMgt = new CancellationTokenSource(); DispatcherOperation operation = DHelper.InvokeOnMain(() => { Application.Current.MainWindow.IsEnabled = false; dlg = DHelper.CreateInstance <Window>(ViewService.DlgProgress); dlg.Owner = Application.Current.MainWindow; dlg.Show(); }); operation.Wait(); return(dlg); }
public bool Check() { _loadingTask.Wait(); ObservableCollection <ArchiveInformationView> archiveCollection = ArchivesList.Archives; foreach (ArchiveInformationView view in archiveCollection) { if (view.Info.IsOptimized) { continue; } ValidationHelper.SetInvalid(ArchivesList, new ValidationResult(false, "Не все архивы оптимизированы")); return(false); } Archives.Initialize(ArchivesList.Archives.Select(view => view.Info).ToArray()); return(true); }
public void Execute(ActionExecutionContext context) { var newTask = new Task <IResult>(() => { #if DEBUG Thread.Sleep(25000); #endif DispatcherOperation disOp = context.Source.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Delegate)((Func <IResult>)(() => { if (this.cancellationTokenSource.IsCancellationRequested) { return(null); } return(this.syncAction()); })) ); var dispatcherOperationStatus = disOp.Wait(); return(disOp.Result as IResult); }, this.cancellationTokenSource.Token ); newTask.ContinueWith(task => { this.viewModel.Finished();; this.Completed?.BeginInvoke( context.Target, new ResultCompletionEventArgs() { WasCancelled = task.IsCanceled, Error = task.Exception }, ar => { }, task.Result ); }); this.viewModel.Start(); newTask.Start(); }
protected void DispatchCommand(Delegate command) { if (command != null) { // Slightly involved form to enable keyboard interrupt to work. executing = true; DispatcherOperation operation = dispatcher.BeginInvoke(DispatcherPriority.Normal, command); //var operation = dispatcher.Invoke(command); while (executing) { if (operation.Status != DispatcherOperationStatus.Completed) { operation.Wait(TimeSpan.FromSeconds(1)); } if (operation.Status == DispatcherOperationStatus.Completed) { executing = false; } } } }
private void ExecutePostExecutionAction() { //int cpt = 0; while (postExecutionAction != null) { DispatcherOperation operation = dispatcher.BeginInvoke(new Action(() => { try { postExecutionAction(); postExecutionAction = null; } catch (COMException) { waitExcelBusy = true; } catch (Exception ex) { postExecutionAction = null; string message = $"'ExcelPostAsynchronousManager.ExecutePostExecutionAction' failed.{ex.Message}"; Logger.Instance.LogException(LogType.Error, ex, message); } })); operation.Wait(); if (waitExcelBusy) { //Interlocked.Increment(ref cpt); //if (cpt >= 10) //{ // postExecutionAction = null; // Logger.Instance.Log(LogType.Error, "'ExcelPostAsynchronousManager.ExecutePostExecutionAction' failed 10 times. Execution stopped !"); //} //else { Thread.Sleep(50); waitExcelBusy = false; } } } }
public void WhenAndIsEnteredIntoTheLoginDialog(string userName, string password) { string userNameCopy = userName; string passwordCopy = password; DispatcherOperation operation = Dispatcher.FromThread(_loginWindowThread).BeginInvoke(DispatcherPriority.Input, new Action(() => { List <TextBox> textBoxes = FindVisualChildren <TextBox>(_loginWindowObject).ToList(); TextBox userNameText = textBoxes.First(t => AutomationProperties.GetAutomationId(t) == SQLiteArrayStore.Resources.AutomationIds.LoginDialog_UsernameText); TextBox passwordText = textBoxes.First(t => AutomationProperties.GetAutomationId(t) == SQLiteArrayStore.Resources.AutomationIds.LoginDialog_PasswordText); userNameText.Clear(); userNameText.Text = userNameCopy; userNameText.RaiseEvent(new RoutedEventArgs(TextBox.TextChangedEvent)); passwordText.Clear(); passwordText.Text = passwordCopy; passwordText.RaiseEvent(new RoutedEventArgs(TextBox.TextChangedEvent)); })); operation.Wait(TimeSpan.FromSeconds(1)); // allow the UI to redraw }
private void CancelCurrentTask() { if (cancellationTokenSource == null) { return; } cancellationTokenSource.Cancel(); try { task.Wait(); imagePreviewTask?.Wait(); } finally { cancellationTokenSource.Dispose(); cancellationTokenSource = null; pause = false; ButtonPause.Content = "_Pause"; ClearBitmapStream(); } }
private void UpdateInterface() { while (true) { DispatcherOperation op = Dispatcher.BeginInvoke(new Action(delegate() { DateTime now = DateTime.Now; TimeSpan elapsed = now - start; TimeSpan remaining = end - now; TimeSpan total = end - start; if (remaining.Ticks <= 0) { if (!MainTextBox.IsFocused) { MainTextBox.Text = "Timer expired"; } if (notifyIcon != null) { notifyIcon.Text = "Timer expired"; } Title = "Orzeszek Timer"; MainProgressBar.Value = 100; TaskbarUtility.SetProgressState(interopHelper.Handle, TaskbarProgressState.NoProgress); if (!notified) { try { notified = true; string exePath = Assembly.GetExecutingAssembly().Location; string exeDir = new FileInfo(exePath).DirectoryName; string soundsDir = System.IO.Path.Combine(exeDir, "Sounds"); SoundPlayer sp = new SoundPlayer(System.IO.Path.Combine(soundsDir, Settings.Default.AlarmSound)); if (Settings.Default.CloseOnFinish || closeOnFinishThisTime) { sp.PlaySync(); } else if (Settings.Default.LoopNotification) { if (notification != null) { notification.Stop(); } notification = sp; notification.PlayLooping(); StopNotificationButton.Visibility = System.Windows.Visibility.Visible; } else { sp.Play(); } if (Settings.Default.PopupOnFinish) { Show(); WindowState = restorableWindowState; Activate(); Topmost = true; Topmost = false; } if (Settings.Default.FlashOnFinish) { TaskbarUtility.StartFlash(interopHelper.Handle); } } catch (Exception) { } } if (Settings.Default.CloseOnFinish || closeOnFinishThisTime) { closeFromTray = true; Close(); } else if (Settings.Default.LoopTimer && Settings.Default.LastTimeSpan != TimeSpan.Zero) { start = DateTime.Now; end = start.Add(Settings.Default.LastTimeSpan); notified = false; } else { updaterThread.Abort(); updaterThread = null; } } else { if (!MainTextBox.IsFocused) { MainTextBox.Text = ToString(remaining); } if (notifyIcon != null) { notifyIcon.Text = ToString(remaining); } Title = MainTextBox.Text; MainProgressBar.Value = Math.Min(100.0, 100.0 * elapsed.Ticks / total.Ticks); TaskbarUtility.SetProgressValue(interopHelper.Handle, (ulong)MainProgressBar.Value, 100); } } )); op.Wait(); Thread.Sleep((int)Math.Max(Math.Min((end - start).TotalSeconds / MainProgressBar.ActualWidth, 1000), 10)); } }
void weatherWorker_DoWork(object sender, DoWorkEventArgs e) { // Get city name from argument string city = (string)e.Argument; city = city.ToLower(); // Add city to address line /*string address = string.Format(@"http://api.openweathermap.org/data/2.5/weather?q={0}&APPID={1}&mode=json&units=metric", city, OpenWeatherMapAppId); * * // Create HTTP request * HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address); * request.Method = "GET"; * * // Get response * HttpWebResponse response = (HttpWebResponse)request.GetResponse(); * * // Read response to string * string jsonString = new StreamReader(response.GetResponseStream()).ReadToEnd();*/ // Simulate downloading from website Thread.Sleep(250); // Check if file exists if (File.Exists(string.Format("Data/{0}.json", city))) { // Get data from file string jsonString; using (FileStream stream = File.OpenRead(string.Format("Data/{0}.json", city))) { using (StreamReader reader = new StreamReader(stream)) { jsonString = reader.ReadToEnd(); } } // Parse json string and get relevant data JObject root = JObject.Parse(jsonString); // Get response code JToken codToken = root["cod"]; if (root.Value <int>("cod") == 200) { // Get temperature and humidity JToken main = root["main"]; decimal temperature = main.Value <decimal>("temp"); decimal humidity = main.Value <decimal>("humidity"); // Get city name string cityName = root.Value <string>("name"); // Get weather description and icon JArray weatherArray = (JArray)root["weather"]; string desc = weatherArray[0].Value <string>("main"); string iconName = weatherArray[0].Value <string>("icon"); ImageSource icon = null; DispatcherOperation op = Application.Current.Dispatcher.BeginInvoke(new Action(() => { icon = new BitmapImage(new Uri("/Icons/" + iconName + ".png", UriKind.RelativeOrAbsolute)); } )); while (op.Status != DispatcherOperationStatus.Completed) { op.Wait(TimeSpan.FromMilliseconds(500)); } // Get sunrise and sunset time JToken sys = root["sys"]; DateTime sunrise = UnixTimeStampToDateTime(sys.Value <long>("sunrise")); DateTime sunset = UnixTimeStampToDateTime(sys.Value <long>("sunset")); // Get wind speed and direction JToken wind = root["wind"]; decimal windSpeed = wind.Value <decimal>("speed"); decimal windDirection = wind.Value <decimal>("deg"); IsWeatherValid = true; Weather = new WeatherInfo(cityName, temperature, humidity, windSpeed, windDirection, desc, icon, sunrise, sunset); } else { // Some error occured JToken message = root["message"]; ErrorMessage = message.Value <string>(); OnPropertyChanged("ErrorMessage"); IsWeatherValid = false; } } else { ErrorMessage = "You can choose only Brno or Praha :( Sorry!"; OnPropertyChanged("ErrorMessage"); IsWeatherValid = false; } }