public void AltF4() { synchronizationContext.Post(delegate { SendKeys.Send("%{F4}"); }, null); }
private void processInvoice(string dir, string invoiceno, int rowNum) { WindowsFormsSynchronizationContext mUiContext = this.mUiContext; SendOrPostCallback d = new SendOrPostCallback(this.UpdateGridText); string filename = dir + Path.DirectorySeparatorChar.ToString() + invoiceno + ".pdf"; InvoiceInfo objA = this.ReadPDF(filename, rowNum); if (!ReferenceEquals(objA, null)) { objA.invFile = filename; Tuple <bool, string> tuple = objA.ValidateReadedData(invoiceno); if (!tuple.Item1) { mUiContext.Post(d, new Tuple <int, string>(rowNum, tuple.Item2)); } else { Tuple <bool, string> tuple2 = objA.FindFiles(dir, objA); if (!tuple2.Item1) { mUiContext.Post(d, new Tuple <int, string>(rowNum, tuple2.Item2)); } else { InvoicePrcessor prcessor = new InvoicePrcessor(); string str2 = prcessor.ProcessInvoice(objA); mUiContext.Post(d, new Tuple <int, string>(rowNum, str2)); prcessor.Dispose(); } } } }
private void ShowNextNotificationMessage() { // Insert retorical comment here... if (messages.Count < 1) { return; } // If the timer is active, it will queue the next message at the appropriate time if (timer != null) { return; } // The code needs to be run in on the UI thread, else, well... synchronizationContext.Post(delegate { /* * if (NotificationForm == null || NotificationForm.IsDisposed) * { * NotificationForm = new NotificationForm(); * } */ NotificationForm.ShowWithMessage(messages.Dequeue()); ScheduleNotificationDismissal(); }, null); }
// The following BeginInvoke() methods follow a boilerplate pattern for how these methods // should be implemented - they differ only in the number of arguments that the caller wants // to provide. public void BeginInvoke(DMethodWithNoParameters methodWithNoParameters) { _synchronizationContext.Post((object stateNotUsed) => { if (!_thread1Control.IsDisposed) { methodWithNoParameters(); } }, null); }
public void onError() { windowsFormsSynchronizationContext.Post(callback => { if (trayIcon != null) { trayIcon.Icon = redIcon; trayIcon.Text = "TCSynchronize: An error occured. See logs for more info."; } }, null); }
public void ToggleShow() { synchronizationContext.Post((state) => { if (Visible) { Hide(); } else { Show(); } }, null); }
public void WindowsFormsSynchronizationContext_Post_InvokeDisposed_Nop(object state) { int callCount = 0; SendOrPostCallback callback = (actualState) => callCount++; var context = new WindowsFormsSynchronizationContext(); context.Dispose(); context.Post(callback, state); Assert.Equal(0, callCount); // Call again. context.Post(callback, state); Assert.Equal(0, callCount); }
private static void Run() { WindowsFormsSynchronizationContext.AutoInstall = false; Utilities.EnableMenuShortcutsUnderlining(); Application.EnableVisualStyles(); Application.SetHighDpiMode(HighDpiMode.PerMonitorV2); Application.SetCompatibleTextRenderingDefault(false); Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); using (var context = new WindowsFormsSynchronizationContext()) { SynchronizationContext.SetSynchronizationContext(context); Application.ThreadException += ThreadExceptionHandler; try { Environment.ExitCode = 0; context.Post(_ => RunAsync(), null); Application.Run(); } catch (Exception ex) { ObserveError(ex); } finally { Application.ThreadException -= ThreadExceptionHandler; SynchronizationContext.SetSynchronizationContext(null); } } }
/// <summary> /// Waits on the UI Thread to complete normally for NavigationOverallTimeout. /// After it attempts shutdown the UI thread graceful followed by aborting /// the thread if a graceful shutdown is not successful. /// </summary> /// <param name="uiThread"></param> /// <returns>Returns true if the UI thread completed on its own before the timeout. Otherwise false.</returns> private void WaitForCompletionOrTimeout(Thread uiThread) { long navigationOverallTimeout = NavigationOverallTimeout; long navigationStartTime = DateTime.Now.Ticks; bool initialized = _threadInitializedEvent.WaitOne((int)navigationOverallTimeout); if (initialized) { // Calculate time remaining after time spend on initialization. // There are 10 000 ticks in each millisecond. long elapsedTimeSinceStart = (DateTime.Now.Ticks - navigationStartTime) / 10000; navigationOverallTimeout -= elapsedTimeSinceStart; bool completedNormally = uiThread.Join(navigationOverallTimeout > 0 ? (int)navigationOverallTimeout : 0); if (!completedNormally) { RequestContext.Logger.Info("Silent login thread did not complete on time."); // The invisible dialog has failed to complete in the allotted time. // Attempt a graceful shutdown. _formsSyncContext.Post(state => _dialog.CloseBrowser(), null); } } }
void Main.Interface.ThempEdit.SynchInvoke(WindowsFormsSynchronizationContext winformcontext, SendOrPostCallback callbackmethod) { object result = OpenEdieView(); //客户端可以通过捕获事件来拿到对象,消除调用和设置之间的耦合 _openeditviewevent(this, (result as Main.Interface.ComeBaseModule.PlugEventArgs)); winformcontext.Post(callbackmethod, null); }
public void WindowsFormsSynchronizationContext_Post_InvokeSameThread_Success(object state) { int callCount = 0; SendOrPostCallback callback = (actualState) => { Assert.Same(state, actualState); callCount++; }; var context = new WindowsFormsSynchronizationContext(); context.Post(callback, state); Assert.Equal(0, callCount); // Call again. context.Post(callback, state); Assert.Equal(0, callCount); }
public void BeginInvoke(Action methodToInvoke) { if (_synchronizationContext == null) { Logging.Debug("UIThread: BeginInvoke called before a _synchronizationContext has been created"); return; } _synchronizationContext.Post(o => methodToInvoke(), null); }
void Invoke(SendOrPostCallback d, object state, bool sync) { if (sync) { sc.Send(d, state); } else { sc.Post(d, state); } }
private void wifi_onConnectedComplete(bool success) { synchronizationContext.Post(delegate { if (success) { userControl_wifiSetupProgress.SetMessage("Connection successful!", ShowWifiStatus); } else { userControl_wifiSetupProgress.SetMessage("Failed to connect. Please try again.", StartWifiSetupWizard); } }, null); }
/// <summary> /// process tasks from the main form via queue /// </summary> private void Consumer() { Task.Run(() => { while (runConsumer) { dataSignal.WaitOne(); try { QueueArgs data = null; while (queueArgs.TryDequeue(out data)) { if (data != null) { switch (data.type) { case OverlayCommand.DEATH: mUiContext.Post(UpdateForm, data); break; case OverlayCommand.VISIBILITY: mUiContext.Post(UpdateVisibility, data); break; case OverlayCommand.MAX_DEATHS: mUiContext.Post(UpdateMaxDeaths, data); break; case OverlayCommand.RESET: mUiContext.Post(Clear, null); break; case OverlayCommand.LOCATE: mUiContext.Post(LocateForm, data); break; case OverlayCommand.REMOVE: mUiContext.Post(RemoveItem, data); break; } } } } catch { } } }); }
private void OnSystemStatusUpdateEvent(SystemStatusUpdateEvent message) { synchronizationContext.Post(delegate { if (message.BatteryPercent != -1) { metroLabel_powerStatus.Text = "Power Level: " + message.BatteryPercent.ToString() + "%"; } if (message.SystemVolumePercent != -1) { metroLabel_systemVolumeStatus.Text = "System Volume: " + message.SystemVolumePercent.ToString() + "%"; } if (message.WifiStatus != null) { metroLabel_networkStatus.Text = "Wifi Status: " + message.WifiStatus; } }, null); }
private static void StartIpcPipe() { //todo: impl a set of IPC APIs to perform some cmds. eg.Pause/Resume, Quit... //todo: Temporay IPC mechanism. var synCtx = new WindowsFormsSynchronizationContext();//note: won't work with `SynchronizationContext.Current` var pipeThread = new Thread(() => { while (true) { using (var server = new System.IO.Pipes.NamedPipeServerStream("WGestures_IPC_API")) { server.WaitForConnection(); Debug.WriteLine("Clien Connected"); using (var reader = new StreamReader(server)) { var cmd = reader.ReadLine(); Debug.WriteLine("Pipe CMD=" + cmd); if (cmd == "ShowSettings") { synCtx.Post((s) => { Debug.WriteLine("Thread=" + Thread.CurrentThread.ManagedThreadId); ShowSettings(); //ToggleTrayIconVisibility(); }, null); } } } } }) { IsBackground = true }; pipeThread.Start(); }
public void HideMessage() { _context.Post(new System.Threading.SendOrPostCallback(_HideMessage), null); }
private static void Main() { InitializeLogger(); Log.Information("Application Starts"); #if !DEBUG AppDomain.CurrentDomain.UnhandledException += (sender, args) => { HandleException((Exception)args.ExceptionObject); }; Log.Information("Set Exception Handler"); Application.ThreadException += Application_ThreadException; Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); WindowsAPIAdapter.Start(Application_ThreadException); #else WindowsAPIAdapter.Start(); #endif Thread.CurrentThread.CurrentUICulture = new LanguageFactory().Get(AppModel.Instance.Language).CultureInfo; Thread.CurrentThread.Name = "Main Thread"; var userMutexName = Application.ProductName + Environment.UserName; using var mainMutex = new Mutex(true, Application.ProductName); using var userMutex = new Mutex(true, userMutexName, out var userMutexInUse); if (KillOtherInstanceAndRestart(userMutexName, userMutexInUse)) { return; } SetProcessDPIAware(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Manage the Closing events send by Windows // Since this app don't use a Form as "main window" the app doesn't close // when it should without this. WindowsAPIAdapter.RestartManagerTriggered += (sender, @event) => { Log.Debug("Restart Event received: {Event}", @event); switch (@event.Type) { case WindowsAPIAdapter.RestartManagerEventType.Query: @event.Result = new IntPtr(1); break; case WindowsAPIAdapter.RestartManagerEventType.EndSession: case WindowsAPIAdapter.RestartManagerEventType.ForceClose: Log.Debug("Close Application"); Application.Exit(); break; } }; Log.Information("Set Tray Icon with Main"); #if !DEBUG try { #endif MMNotificationClient.Instance.Register(); using var ctx = new WindowsFormsSynchronizationContext(); using var icon = new TrayIcon(); SynchronizationContext.SetSynchronizationContext(ctx); try { ctx.Post(async iconState => await InitAsync((TrayIcon)iconState), icon); Application.Run(); } finally { SynchronizationContext.SetSynchronizationContext(null); } #if !DEBUG } catch (Exception ex) { HandleException(ex); } #endif AppModel.Instance.ActiveAudioDeviceLister.Dispose(); AppModel.Instance.ActiveUnpluggedAudioLister.Dispose(); MMNotificationClient.Instance.UnRegister(); WindowsAPIAdapter.Stop(); Log.CloseAndFlush(); }
/// <summary> /// OnStrategyStateChangedEvent event /// </summary> /// <param name="state"></param> /// <param name="isFinal"></param> private void OnStrategyStateChangedEvent(int[] state, bool isFinal) { synchronizationContext.Post(item => DisplayState(state, isFinal), null); Thread.Sleep(1500); }
public override void Post(SendOrPostCallback d, object state) { baseContext.Post(d, state); }
private void start_process(List <string> strs, Project prj, DateTime now) { var part = Partitioner.Create(strs); var task_factory = Task.Factory.StartNew <ParallelLoopResult>(() => Parallel.ForEach(part, new ParallelOptions() { MaxDegreeOfParallelism = prj.thread_count }, (refNum) => { //string refNum = strs[i_str]; //ShowMessageBox(" "+refNum); DataGridViewRow row = ( from DataGridViewRow dataGridViewRow in this.grdCases.Rows where dataGridViewRow.Cells[0].Value.ToString().Equals(refNum) select dataGridViewRow).First <DataGridViewRow>(); TimeSpan procTime = new TimeSpan(); string result = null; while (result != "0") { WindowsFormsSynchronizationContext windowsFormsSynchronizationContext = this.mUiContext; SendOrPostCallback sendOrPostCallback = new SendOrPostCallback(this.UpdateGUIConsole); string str = refNum.ToString(); int managedThreadId = Thread.CurrentThread.ManagedThreadId; windowsFormsSynchronizationContext.Post(sendOrPostCallback, string.Concat("Processing ", str, " on thread ", managedThreadId.ToString())); if (row.Cells[2].Value != null) { DataGridViewCell item = row.Cells[2]; managedThreadId = Thread.CurrentThread.ManagedThreadId; item.Value = string.Concat("Re-Processing on thread ", managedThreadId.ToString()); } else { DataGridViewCell dataGridViewCell = row.Cells[2]; managedThreadId = Thread.CurrentThread.ManagedThreadId; dataGridViewCell.Value = string.Concat("Processing on thread ", managedThreadId.ToString()); } this.mUiContext.Post(new SendOrPostCallback(this.UpdateGUI), null); DateTime begin = DateTime.Now; Locate locator = new Locate(); listLoacte.Add(locator); locator.showMessage = ShowMessageBox; bool is_logged_in = locator.Login(prj.Username, prj.Password); if (!is_logged_in) { result = "Login Failed"; locator.quit(); } else { result = locator.LocateCase(refNum, this.grdCases, prj.Path); locator.logout(); } procTime = DateTime.Now - begin; if (result != "0") { row.Cells[2].Value = "Error Processing"; this.mUiContext.Post(new SendOrPostCallback(this.UpdateGUI), null); this.mUiContext.Post(new SendOrPostCallback(this.UpdateGUIConsole), string.Concat("Error Processing ", refNum.ToString(), ":")); this.mUiContext.Post(new SendOrPostCallback(this.UpdateGUIConsole), result); } } row.Cells[2].Value = string.Concat(new object[] { "Completed in ", procTime.Minutes, " minutes ", procTime.Seconds, " seconds" }); this.mUiContext.Post(new SendOrPostCallback(this.UpdateGUIConsole), string.Concat(new object[] { "Completed ", refNum, " in ", procTime.Minutes, " minutes ", procTime.Seconds, " seconds" })); this.mUiContext.Post(new SendOrPostCallback(this.UpdateGUIComplete), null); this.mUiContext.Post(new SendOrPostCallback(this.UpdateGUI), null); Thread.Sleep(100); })).ContinueWith((Task <ParallelLoopResult> tsk) => this.EndTweets(tsk, now)); }
void mStrategy_OnStateChanged(int[] currentState, bool isFinal) { mSyncContext.Post(item => DisplayState(currentState, isFinal), null); Thread.Sleep(GameProperties.SPEED_TIMER_INTERVAL); }
public void BeginInvoke(Action methodToInvoke) { if(_synchronizationContext == null) return; _synchronizationContext.Post(o => methodToInvoke(), null); }
public static void EnqueueSyncTask(Delegate taskHandler, object param) { _syncContext.Post(new EventTask(taskHandler).Invoke, param); }
private void HideHomeScreen() { // Hiding the home screen really just means hiding the main form synchronizationContext.Post(delegate { Hide(); }, null); }
private void OnStrategyStateChanged(int[] state, bool isFinal) { mSyncContext.Post(item => DisplayState(state, isFinal), null); Thread.Sleep(1000); }
private void workerLoadFolders_ProgressChanged(object sender, ProgressChangedEventArgs e) { // For thread synchronization _syncContext.Post(workerLoadFolders_ProgressChanged_Callback, e); }
public void Invoke(Action callback) { context.Post((s) => { callback(); }, null); }
public static void EnqueueSyncTask(Delegate taskHandler, object param) { //All these tasks will run one-by-one in order on Main thread //either on call of Application.DoEvenets or when Main thread becomes idle _syncContext.Post(new EventTask(taskHandler).Invoke, param); }