protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { if (SynchronizationContext.Current == synchronizationContext) { RaiseCollectionChanged(e); } else { synchronizationContext?.Send(RaiseCollectionChanged, e); } }
private void FillTableAsync(string tableLink, NodeType type, ICollection <Schedule> result, SynchronizationContext context, bool waitForFinish) { Thread local = new Thread(() => { using (WebClient client = new WebClient()) { try { var preResult = FillTable(type, client.DownloadString(tableLink)); context?.Send(t => { foreach (var schedule in preResult) { result.Add(schedule); } }, null); } catch (Exception e) { ExceptionEvent?.Invoke(e); } } }); local.Start(); if (waitForFinish) { local.Join(); } }
public override void Send(SendOrPostCallback d, object state) { lock (_lock) { if (_ctx != null) { _ctx?.Send(d, state); } else { d(state); } } }
public static void CreateMsg(object sender, string msg, params object[] args) { var lMessage = msg; if (args != null && args.Length > 0) { lMessage = string.Format(msg, args); } if (Instance.OnMessage != null) { mSyncContext?.Send(d => Instance.OnMessage(sender, new MessageEventArgs(lMessage)), null); } }
private void OnFileReadOperationFinished(FileTransferManager.FileTransferResultInfo in_result) { if (in_result.State == FileTransferManager.FileTransferResult.Success) { m_files_info[m_current_file_index].FullPath = in_result.FullPath; m_files_info[m_current_file_index].FileID = in_result.FileID; if (m_current_file_index < m_files_info.Length - 1) { m_current_file_index++; OnPropertyChanged("CurrentFileIndex"); CommunicationManager.Default.FileTransfer.FileDownloadStart(m_files_info[m_current_file_index].Name, OnFileReadOperationFinished); } else { m_synchronization_context.Send(FileReadOperationFinishedSync, null); } } else { // TODO error handling } }
public static void InvokeSync(this Control control, SendOrPostCallback action, object state) { SendOrPostCallback checkDisposedAndInvoke = (s) => { if (!control.IsDisposed) { action(s); } }; if (!control.IsDisposed) { UISynchronizationContext.Send(checkDisposedAndInvoke, state); } }
/// <summary> /// Initializes a new instance of the /// <see cref="PropertyObserverOnValueChangedWithFallback{TParameter1, TParameter2, TResult}" /> /// class. /// </summary> /// <param name="parameter1">The parameter1.</param> /// <param name="parameter2">The parameter2.</param> /// <param name="propertyExpression">The property expression.</param> /// <param name="synchronizationContext">The synchronization context.</param> /// <param name="fallback">The fallback.</param> /// <param name="observerFlag">The observer flag.</param> internal PropertyObserverOnValueChangedWithFallback( [NotNull] TParameter1 parameter1, [NotNull] TParameter2 parameter2, [NotNull] Expression <Func <TParameter1, TParameter2, TResult> > propertyExpression, [NotNull] SynchronizationContext synchronizationContext, [NotNull] TResult fallback, PropertyObserverFlag observerFlag) : base(parameter1, parameter2, propertyExpression, observerFlag) { this.value = fallback; var get = this.CreateGetter(Getter(propertyExpression, this.Tree, fallback, parameter1, parameter2)); this.action = () => synchronizationContext.Send(() => this.Value = get()); this.getValue = this.CreateGetProperty(() => this.value); }
public async Task ProcessTopicMessagesAsync(Message message, CancellationToken token) { // Process the message. string val = $"{Encoding.UTF8.GetString(message.Body)}"; // check if the message is json encoded if (val.StartsWith("{") && val.EndsWith("}") && _TopicHandler != null) { // close recieved message await _TopicHandler.CompleteMessageAsync(message.SystemProperties.LockToken); // send message to the setResponse method _currentSynchronizationContext.Send(x => setResponse(val), null); } }
private IEnumerator PlayQueue() { IAlert alert = _queuedAlerts.Peek(); _synchronizationContext.Send(SafeInvokeSpawn, alert); yield return(new WaitForSecondsRealtime(alert.Lifeline)); yield return(new WaitForSecondsRealtime(alert.Flatline)); _queuedAlerts.Dequeue(); if (_queuedAlerts.Count != 0) { StartCoroutine(PlayQueue()); } }
private void DrawRectangle(SynchronizationContext context, int i) { while (true) { lock (sync) { if (points[i] != lastPoints[i]) { context.Send((v) => DrawRectangle(points[i], canvases[i], brushes[i]), null); lastPoints[i] = points[i]; } } Thread.Sleep(100); } }
public static void SyncSend(SendOrPostCallback d, object state) { if (SyncContext != null) { SyncContext.Send(d, state); } else { #if !SILVERLIGHT _dispatcher.Invoke(d, state); #else _dispatcher.BeginInvoke(d, state); #endif } }
/// <summary> /// Вечный метод отдельного потока обновления данных на форме. /// </summary> /// <param name="param">Контекст синхронизации.</param> private void DataReload(object param) { while (true) { SynchronizationContext sc = (SynchronizationContext)param; try { sc.Send(_ReloadFormData, GetData()); } catch { } Thread.Sleep(10); } }
private void Render_ImageUpdated(object sender, Game.ImageDrawnEventArgs e) { try { context.Send(o => { pictureBox1.Image = e.Image; pictureBox1.Refresh(); }, null); } catch (InvalidAsynchronousStateException) { ; } }
private void CheckFileExists(string fileName) { if (_overwrite || !File.Exists(fileName)) { return; } _synchronizationContext.Send( delegate { _canceled = DialogBoxAction.No == DesktopWindow.ShowMessageBox(SR.MessageConfirmOverwriteFiles, MessageBoxActions.YesNo); }, null); _overwrite = !_canceled; }
public bool ShowLogin(object o) { var url = new Uri(o.ToString()); if (o == null) { throw new ArgumentException(Dynamo.Wpf.Properties.Resources.InvalidLoginUrl); } var navigateSuccess = false; // show the login context.Send((_) => { var window = new BrowserWindow(url) { Title = Dynamo.Wpf.Properties.Resources.AutodeskSignIn, Owner = parent, WindowStartupLocation = WindowStartupLocation.CenterOwner }; window.Browser.Navigated += (sender, args) => { // if the user reaches this path, they've successfully logged in // note that this is necessary, but not sufficient for full authentication if (args.Uri.LocalPath == "/OAuth/Allow") { navigateSuccess = true; window.Close(); } }; window.ShowDialog(); }, null); return(navigateSuccess); }
public void UpdateRepresentation(EStatus status, SynchronizationContext context) { BrushConverter bc = new BrushConverter(); if (m_sender == m_user) { context.Send(o => { m_nick_range.ApplyPropertyValue(TextElement.ForegroundProperty, bc.ConvertFromString("Red")); }, null); } else { context.Send(o => { m_nick_range.ApplyPropertyValue(TextElement.ForegroundProperty, bc.ConvertFromString("Blue")); }, null); } switch (status) { case EStatus.Sending: context.Send(o => { m_date_range.ApplyPropertyValue(TextElement.FontStyleProperty, FontStyles.Italic); m_nick_range.ApplyPropertyValue(TextElement.FontStyleProperty, FontStyles.Italic); m_message_range.ApplyPropertyValue(TextElement.FontStyleProperty, FontStyles.Italic); }, null); break; case EStatus.Sent: context.Send(o => { m_date_range.ApplyPropertyValue(TextElement.FontStyleProperty, FontStyles.Normal); m_nick_range.ApplyPropertyValue(TextElement.FontStyleProperty, FontStyles.Italic); m_message_range.ApplyPropertyValue(TextElement.FontStyleProperty, FontStyles.Italic); }, null); break; case EStatus.FailedToSend: context.Send(o => { m_date_range.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red); }, null); break; case EStatus.Delivered: context.Send(o => { m_date_range.ApplyPropertyValue(TextElement.FontStyleProperty, FontStyles.Normal); m_nick_range.ApplyPropertyValue(TextElement.FontStyleProperty, FontStyles.Normal); m_message_range.ApplyPropertyValue(TextElement.FontStyleProperty, FontStyles.Italic); }, null); break; case EStatus.Seen: context.Send(o => { m_date_range.ApplyPropertyValue(TextElement.FontStyleProperty, FontStyles.Normal); m_nick_range.ApplyPropertyValue(TextElement.FontStyleProperty, FontStyles.Normal); m_message_range.ApplyPropertyValue(TextElement.FontStyleProperty, FontStyles.Normal); }, null); break; } }
public void GetInfGroup(object context) { SynchronizationContext contextSync = (SynchronizationContext)context; VkAPI _ApiRequest = new VkAPI(token); DBContext dal = new DBContext(); _ApiRequest.DecrementCountGroupId += _ApiRequest_decrementMaxGroupId; while (!_cancel) { strId = ""; contextSync.Send(OnGetGroupsProcessing, "Getting groups ID starting with " + _maxGroupId); for (int i = 1; i <= _count; i++) { _maxGroupId += 1; strId += _maxGroupId; if (i < _count) { strId += ","; } } try { _lstGroup = _ApiRequest.GetInfGroup(strId); dal.WriteDBSQL(_lstGroup); } catch (Exception e) { contextSync.Send(OnGetGroupsException, e); contextSync.Send(OnGetGroupsProcessing, "Error"); break; } contextSync.Send(OnGetLastGroupId, _maxGroupId); contextSync.Send(OnGetGroupsProcessing, "Groups ID saved up to " + _maxGroupId); if (decremFlag) { contextSync.Send(OnDecrementCountGroupId, _count); decremFlag = false; } } contextSync.Send(OnStopGetGroupId, true); }
private Template.RegistrationAlignmentMethod.KazeRegistrationMethod.KazeData GetKazeData() { bool extended = false; bool upright = false; float descThresh = 0.001f; int descOcts = 1; int descSbls = 4; var diffType = KAZE.Diffusivity.PmG2; synchronizationContext.Send(new SendOrPostCallback( delegate(object state) { extended = kazeExtendedToggle.ToggleState == ToggleButtonState.Active; upright = kazeUprightToggle.ToggleState == ToggleButtonState.Active; descThresh = (float)kazeThresholdValueBox.DoubleValue; descOcts = (int)kazeOctavesValueBox.IntegerValue; descSbls = (int)kazeSublvlsValueBox.IntegerValue; diffType = (KAZE.Diffusivity)kazeDiffTypeValueBox.SelectedIndex; } ), null); Template.RegistrationAlignmentMethod.KazeRegistrationMethod.KazeData kazeData = new Template.RegistrationAlignmentMethod.KazeRegistrationMethod.KazeData(extended, upright, descThresh, descOcts, descSbls, diffType); return(kazeData); }
private void AudioStreamer_StateChanged() { syncContext.Send(_ => { //UpdateAudioControls(); }, null); if (audioStreamer.IsStreaming) { } else { audioStreamer.StateChanged -= AudioStreamer_StateChanged; } }
static void RaiseOnUIThread(EventHandler handler, object sender) { if (handler != null) { SynchronizationContext uiSyncContext = SynchronizationContext.Current ?? new SynchronizationContext(); if (uiSyncContext == null) { handler(sender, EventArgs.Empty); } else { uiSyncContext.Send(delegate { handler(sender, EventArgs.Empty); }, null); } } }
private void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { if (m_SyncContext == null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } else { //此处采用上下文同步方式发送消息,你当然也可以使用异步方式发送,异步方法为m_SyncContext.Post m_SyncContext.Send(p => PropertyChanged(this, new PropertyChangedEventArgs(propertyName)), null); } } }
public void Run(Action Action, bool Async = false) { if (_syncContext == null) { Action(); } else if (Async) { _syncContext.Post(D => Action(), null); } else { _syncContext.Send(D => Action(), null); } }
private void Window_Loaded(object sender, RoutedEventArgs e) { buttonSend.IsEnabled = false; SynchWindow = SynchronizationContext.Current; ThreadRead = new Thread(FrameReceiving); ThreadCheckConn = new Thread(Connect); string[] ArrayOfPorts; ArrayOfPorts = SerialPort.GetPortNames(); foreach (string port in ArrayOfPorts) { var NewItem = new ComboBoxItem(); NewItem.Content = port; SynchWindow.Send(d => PortsList.Items.Add(NewItem), null); } }
// Start is called before the first frame update void Start() { context = new SynchronizationContext(); Debug.Log($"main thread id:{Thread.CurrentThread.ManagedThreadId}"); var thread = new Thread(ThreadMethod); thread.Start(); Thread.Sleep(6000); Debug.Log("main thread uses synchronizationContext:"); context.Send(EventMethod, "main thread Send"); context.Post(EventMethod, "main thread post"); Debug.Log("main thread finish"); }
public void Skip(int NumToSkip) { for (int i = 0; i < NumToSkip; i++) { syncContext.Send(ExecuteOnMainThread, new MainThreadParams() { EventType = EventType.Skipped }); } }
internal async Task ProcessRequestAsync(HttpContext context, TaskAsyncActionHandler handler) { if (context == null) { throw new ArgumentNullException("context"); } if (handler == null) { throw new ArgumentNullException("handler"); } this.HttpContext = context; this.Handler = handler; this.InvokeInfo = handler.InvokeInfo; // 设置 BaseController 的相关属性 SetController(); // 在异步执行前,先保存当前同步上下文的实例,供异步完成后执行切换调用。 SynchronizationContext syncContxt = SynchronizationContext.Current; if (syncContxt == null) { throw new InvalidProgramException(); } // 进入请求处理阶段 ExecuteBeginRequest(); // 安全检查 ExecuteSecurityCheck(); // 授权检查 ExecuteAuthorizeRequest(); // 执行 Action object actionResult = await ExecuteActionAsync(); // 切换到原先的上下文环境,执行余下操作 syncContxt.Send(x => { // 设置输出缓存 SetOutputCache(); // 处理方法的返回结果 ExecuteProcessResult(actionResult); }, this.HttpContext); }
public bool ShowLogin(object o) { if (o == null) { throw new ArgumentException(Resources.InvalidLoginUrl); } // URL shouldn't be empty. // URL can be empty, if user's local date is incorrect. // This a known bug, described here: https://github.com/DynamoDS/Dynamo/pull/6112 if (o.ToString().Length == 0) { MessageBox.Show(Resources.InvalidTimeZoneMessage, Resources.InvalidLoginUrl, MessageBoxButton.OK, MessageBoxImage.Error); return(false); } var url = new Uri(o.ToString()); var navigateSuccess = false; // show the login context.Send(_ => { var window = new BrowserWindow(url) { Title = Resources.AutodeskSignIn, Owner = parent, WindowStartupLocation = WindowStartupLocation.CenterOwner }; window.Browser.Navigated += (sender, args) => { // if the user reaches this path, they've successfully logged in // note that this is necessary, but not sufficient for full authentication if (args.Uri.LocalPath == "/OAuth/Allow") { navigateSuccess = true; window.Close(); } }; window.ShowDialog(); }, null); return(navigateSuccess); }
protected override void OnAddingNew(AddingNewEventArgs e) { SynchronizationContext ctx = SynchronizationContext.Current; if (ctx == null) { BaseAddingNew(e); } else { ctx.Send(delegate { BaseAddingNew(e); }, null); } }
/// <summary> /// Convenience method to execute a function within given SynchronizationContext. /// </summary> /// <param name="syncContext"></param> /// <param name="delegate"></param> public static void Execute(this SynchronizationContext syncContext, Action @delegate) { if (syncContext == null) { @delegate(); return; } #if !DEBUG if (syncContext == SynchronizationContext.Current) { @delegate(); return; } #endif syncContext.Send(delegate { @delegate(); }, null); }
/// <summary> /// Convenience method to execute a function within given SynchronizationContext. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="syncContext"></param> /// <param name="delegate"></param> /// <returns></returns> public static T Execute <T>(this SynchronizationContext syncContext, Func <T> @delegate) { if (syncContext == null) { return(@delegate()); } #if !DEBUG if (syncContext == SynchronizationContext.Current) { return(@delegate()); } #endif T retVal = default(T); syncContext.Send(delegate { retVal = @delegate(); }, null); return(retVal); }