private void App_AppServiceDisconnected(object sender, EventArgs e) { _inited = false; _context?.Post(async _ => { ToastHelper.SendToast("MLHelperDownTip".GetLocalized(), TimeSpan.FromSeconds(3)); await Task.Delay(500); await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); }, null); }
private void OnWebSocketMessageReceive(object sender, MessageEventArgs e) { if (!e.IsText) { return; } var typeJson = JsonUtility.FromJson <JsonData.GrayBlueJson <object> >(e.Data); switch (typeJson.Type) { case JsonData.JsonType.Result: var result = JsonUtility.FromJson <JsonData.GrayBlueJson <JsonData.MethodResult> >(e.Data).Content; requestAgent?.ExtractResultJson(result); break; case JsonData.JsonType.DeviceStateChange: var device = JsonUtility.FromJson <JsonData.GrayBlueJson <JsonData.Device> >(e.Data).Content; if (device.State == "Lost") { context?.Post(_ => { connectDelegate?.OnConnectLost(device.DeviceId); }, null); } break; case JsonData.JsonType.NotifyIMU: var imuJson = JsonUtility.FromJson <JsonData.GrayBlueJson <JsonData.IMU> >(e.Data).Content; var imuData = JsonDataExtractor.ToIMUNotifyData(imuJson); context?.Post(_ => { notifyDelegate?.OnIMUDataUpdate(imuData.deviceId, imuData.acc, imuData.gyro, imuData.mag, imuData.quat); }, null); break; case JsonData.JsonType.NotifyButton: var btnJson = JsonUtility.FromJson <JsonData.GrayBlueJson <JsonData.Button> >(e.Data).Content; var btnData = JsonDataExtractor.ToButtonNotifyData(btnJson); context?.Post(_ => { if (btnData.isPress) { notifyDelegate?.OnButtonPush(btnData.deviceId, btnData.button); } else { notifyDelegate?.OnButtonRelease(btnData.deviceId, btnData.button, btnData.time); } }, null); break; default: // Do Nothing break; } }
void Progres() { SynchronizationContext context = SynchronizationContext.Current; Thread backgroundThread = new Thread( new ThreadStart(() => { for (int n = 0; n < 1000; n++) { Thread.Sleep(5); context?.Post(new SendOrPostCallback((o) => { ProgressBar.Value = n; }), null); if (n.Equals(999)) { this.Dispatcher.Invoke(() => { sw.Stop(); StudyPageViewAction.ChangeStudyPage(sw.Elapsed, 1); }); } } ; } )); backgroundThread.Start(); }
// ---------------------------------------------------------------------------- // // // SDKを自動停止させるための関数 // // ---------------------------------------------------------------------------- // private void AutoStopTask() { mContext?.Post(__ => { Speak.Instance().Stop(OnStop); }, null); }
void Log(LogLevel level, Action <TraceRecord> traceAction, [CallerMemberName] string member = "", [CallerLineNumber] int line = 0) { // Check if this log level is enabled and client is subscribed to the OnLog event if (OnLog == null || this.LogLevel >= level) { return; } TraceRecord tr = new TraceRecord() { Level = level }; traceAction(tr); string message = $"{member}() line {line}: {tr.Message}"; if (UseSynchronizationContextForEvents && syncContext != null && syncContext != SynchronizationContext.Current) { syncContext?.Post(o => OnLog?.Invoke(this, new LogEventArgs() { LogLevel = level, Message = message, Exception = tr.Exception }), null); } else { OnLog?.Invoke(this, new LogEventArgs() { LogLevel = level, Message = message, Exception = tr.Exception }); } }
public void LogOut(string str) { lock (this) { if (Config.debug) { Console.Error.WriteLine(str); Console.Error.Flush(); } str = string.Format("[{0}] {1}\r\n", DateTime.Now.ToString(), str); LogStream?.Write(str); LogStream?.Flush(); if (Config.IsClosing) { return; } synchronizationContext?.Post( (o) => { if (Config.IsClosing) { return; } SendMessage(textBox1.Handle, EM_REPLACESEL, 1, o as string); }, str); } }
internal void Post(IntPtr function_ptr) { _context?.Post(f_ptr => { scheduler_invoke_function((IntPtr)f_ptr, !_isReleased); }, function_ptr); }
/// <summary> /// Метод, используемый для создания события <see cref="CanExecuteChanged"/> /// чтобы показать, что возвращаемое значение <see cref="CanExecute"/> /// метод изменился. /// </summary> public void RaiseCanExecuteChanged() { if (CanExecuteChanged != null) { _context?.Post(s => { CanExecuteChanged?.Invoke(this, EventArgs.Empty); }, null); } }
private static void update() { syncContext = SynchronizationContext.Current ?? syncContext; Effect.UpdateAsync().ContinueWith(t => { syncContext?.Post(_ => { t.Wait(); }, null); }); }
private void OnPluginStateChanged(PluginStateChanged state) { _synccontext?.Post(_ => { switch (state) { case PluginStateChanged.CurrentHDRStateChanged: Repaint(); break; } }, null); }
/// <summary> /// 重写属性发生改变事件处理函数。 /// </summary> /// <param name="e"></param> protected override void OnPropertyChanged(PropertyChangedEventArgs e) { if (SynchronizationContext.Current == _synchronizationContext) { //如果操作发生在UI线程中,不需要进行跨线程执行 RaisePropertyChanged(e); } else { // 如果操作发生在非UI线程中 _synchronizationContext?.Post(RaisePropertyChanged, e); } }
void UpdateQuaternion(AxisOrangeData data) { var unityData = new AxisOrangeUnityData(data); if (baseQuaternion == Quaternion.identity) { baseQuaternion = unityData.quaternion; } // メインスレッドで実行しないと反映されない context?.Post(_ => { m5stickC.rotation = Quaternion.Inverse(baseQuaternion) * unityData.quaternion; }, null); }
public override void Post(SendOrPostCallback d, object?state) { lock (_lock) { if (_ctx is not null) { _ctx?.Post(d, state); } else { d(state); } } }
void INotifyDelegate.OnIMUDataUpdate(string deviceId, float[] acc, float[] gyro, float[] mag, float[] quat) { if (sensorEventDict.ContainsKey(deviceId)) { var accVal = new Vector3(acc[0], acc[1], acc[2]); var gyroVal = new Vector3(gyro[0], gyro[1], gyro[2]); var magVal = new Vector3(mag[0], mag[1], mag[2]); var quatVal = new Quaternion(quat[0], quat[1], quat[2], quat[3]); var raw = new SensorData { acc = accVal, gyro = gyroVal, mag = magVal, quat = quatVal }; var imu = new IMUData { timeUtc = DateTime.UtcNow, raw = raw, unity = raw.ToUnityWorld() }; var device = sensorEventDict[deviceId]; context?.Post(_ => { device.NotifyUpdateAccel(accVal); device.NotifyUpdateGyro(gyroVal); device.NotifyUpdateCompass(magVal); device.NotifyUpdateQuaternion(quatVal); device.NotifyUpdateIMU(imu); }, null); } }
private void ScheduleToBeLoadedInMainThread(Action lambda) { _synchronizationContext.Post(delegate { lambda.Invoke(); }, null); }
/// <summary> /// Raises this object's PropertyChanged event. /// </summary> /// <param name="args">The PropertyChangedEventArgs</param> protected virtual void OnPropertyChanged(PropertyChangedEventArgs args) => context?.Post(d => { PropertyChanged?.Invoke(this, args); }, null);
private void Layer_Loaded(object sender, System.EventArgs e) { (sender as ILoadable).Loaded -= Layer_Loaded; _syncContext?.Post(_ => Refresh(), null); }
private void HandleAuthorizationResponse(AuthorizationResponse response) { // This method is called on a background thread; rerouting it to the Unity's thread. unitySyncContext.Post(HandleAuthorizationResponseOnUnityThread, response); }
/// <summary> /// Raises this object's PropertyChanged event. /// </summary> /// <param name="args">The PropertyChangedEventArgs</param> protected virtual void OnPropertyChanged(PropertyChangedEventArgs args) => context?.Post(d => { this.NotifyPropertyChanged(args.PropertyName); }, null);
void RunTaskOn(SynchronizationContext on, Task task) { on?.Post(async _ => { await task; }, null); }
public IDisposable BlockAllOperations() { if (isDisposed) { throw new ObjectDisposedException(nameof(RealmAccess)); } SynchronizationContext?syncContext = null; try { realmRetrievalLock.Wait(); lock (realmLock) { if (updateRealm == null) { // null realm means the update thread has not yet retrieved its instance. // we don't need to worry about reviving the update instance in this case, so don't bother with the SynchronizationContext. Debug.Assert(!ThreadSafety.IsUpdateThread); } else { if (!ThreadSafety.IsUpdateThread) { throw new InvalidOperationException(@$ "{nameof(BlockAllOperations)} must be called from the update thread."); } syncContext = SynchronizationContext.Current; // Before disposing the update context, clean up all subscriptions. // Note that in the case of realm notification subscriptions, this is not really required (they will be cleaned up by disposal). // In the case of custom subscriptions, we want them to fire before the update realm is disposed in case they do any follow-up work. foreach (var action in customSubscriptionsResetMap) { action.Value?.Dispose(); customSubscriptionsResetMap[action.Key] = null; } } Logger.Log(@"Blocking realm operations.", LoggingTarget.Database); updateRealm?.Dispose(); updateRealm = null; } const int sleep_length = 200; int timeout = 5000; try { // see https://github.com/realm/realm-dotnet/discussions/2657 while (!Compact()) { Thread.Sleep(sleep_length); timeout -= sleep_length; if (timeout < 0) { throw new TimeoutException(@"Took too long to acquire lock"); } } } catch (RealmException e) { // Compact may fail if the realm is in a bad state. // We still want to continue with the blocking operation, though. Logger.Log($"Realm compact failed with error {e}", LoggingTarget.Database); } // In order to ensure events arrive in the correct order, these *must* be fired post disposal of the update realm, // and must be posted to the synchronization context. // This is because realm may fire event callbacks between the `unregisterAllSubscriptions` and `updateRealm.Dispose` // calls above. syncContext?.Send(_ => { // Flag ensures that we don't get in a deadlocked scenario due to a callback attempting to access `RealmAccess.Realm` or `RealmAccess.Run` // and hitting `realmRetrievalLock` a second time. Generally such usages should not exist, and as such we throw when an attempt is made // to use in this fashion. isSendingNotificationResetEvents = true; try { foreach (var action in notificationsResetMap.Values) { action(); } } finally { isSendingNotificationResetEvents = false; } }, null); } catch { restoreOperation(); throw; } return(new InvokeOnDisposal(restoreOperation)); void restoreOperation() { Logger.Log(@"Restoring realm operations.", LoggingTarget.Database); realmRetrievalLock.Release(); // Post back to the update thread to revive any subscriptions. // In the case we are on the update thread, let's also require this to run synchronously. // This requirement is mostly due to test coverage, but shouldn't cause any harm. if (ThreadSafety.IsUpdateThread) { syncContext?.Send(_ => ensureUpdateRealm(), null); } else { syncContext?.Post(_ => ensureUpdateRealm(), null); } } }
void HandleElapsed(object?state) { _context?.Post((o) => SendSignals(-1), null); }
public RecordingViewModel(RecordingModel RecordingModel, Settings Settings, TimerModel TimerModel, WebcamModel WebcamModel, VideoSourcesViewModel VideoSourcesViewModel, VideoWritersViewModel VideoWritersViewModel, ISystemTray SystemTray, IMainWindow MainWindow, ILocalizationProvider Loc, IAudioPlayer AudioPlayer, IRecentList RecentList, IMessageProvider MessageProvider, AudioSourceViewModel AudioSourceViewModel, IFFmpegViewsProvider FFmpegViewsProvider) : base(Settings, Loc) { _recordingModel = RecordingModel; _timerModel = TimerModel; _videoSourcesViewModel = VideoSourcesViewModel; _videoWritersViewModel = VideoWritersViewModel; _systemTray = SystemTray; _mainWindow = MainWindow; _audioPlayer = AudioPlayer; _recentList = RecentList; _messageProvider = MessageProvider; _audioSourceViewModel = AudioSourceViewModel; _ffmpegViewsProvider = FFmpegViewsProvider; var hasAudio = new[] { Settings .Audio .ObserveProperty(M => M.RecordMicrophone), Settings .Audio .ObserveProperty(M => M.RecordSpeaker) } .CombineLatest(M => M[0] || M[1]); RecordCommand = new[] { hasAudio, VideoSourcesViewModel .ObserveProperty(M => M.SelectedVideoSourceKind) .Select(M => M is NoVideoSourceProvider), VideoSourcesViewModel .ObserveProperty(M => M.SelectedVideoSourceKind) .Select(M => M is WebcamSourceProvider), WebcamModel .ObserveProperty(M => M.SelectedCam) .Select(M => M is NoWebcamItem) } .CombineLatest(M => { var audioEnabled = M[0]; var audioOnlyMode = M[1]; var webcamMode = M[2]; var noWebcam = M[3]; if (audioOnlyMode) { return(audioEnabled); } if (webcamMode) { return(!noWebcam); } return(true); }) .ToReactiveCommand() .WithSubscribe(OnRecordExecute); PauseCommand = new[] { TimerModel .ObserveProperty(M => M.Waiting), RecordingModel .ObserveProperty(M => M.RecorderState) .Select(M => M != Models.RecorderState.NotRecording) } .CombineLatest(M => !M[0] && M[1]) .ToReactiveCommand() .WithSubscribe(() => { _audioPlayer.Play(SoundKind.Pause); RecordingModel.OnPauseExecute(); }); RecorderState = RecordingModel .ObserveProperty(M => M.RecorderState) .ToReadOnlyReactivePropertySlim(); TimerModel.DurationElapsed += async() => { if (_syncContext != null) { _syncContext.Post(async State => await StopRecording(), null); } else { await StopRecording(); } }; }
void UpdateMessage(string message) { // Marshal the delegate to the UI thread: 消息封送,同步上下文 // _uiSyncContext 为 null _uiSyncContext?.Post(_ => txtMessage.Text = message, null); }
private void OnSourceEndPropertyChanged(object sender, PropertyChangedEventArgs e) { if (context != null && SynchronizationContext.Current != context) { context.Post((o) => { SynchronizationContext.SetSynchronizationContext(context); OnSourceEndPropertyChanged(sender, e); }, this); return; } if (Mode == BindingMode.OneWayToSource) { return; } var sourceToken = SourcePath.Substring(SourcePath.LastIndexOf('.') + 1); if (e.PropertyName != sourceToken) { return; } var targetObject = targetObjects.Last().Target; if (targetObject == null) { Deactivate(); return; } var targetType = targetObject.GetType(); var targetInfo = targetInfos.Last(); var sourceObject = sourceObjects.Last(); object value = null; if (sourceObject.GetType().IsArray) { value = ((Array)sourceObject).GetValue(sourceIndices.Last().Cast <int>().ToArray()); } else { value = sourceInfos.Last().GetValue(sourceObject, sourceIndices.Last()); } if (ValueConverter != null) { value = ValueConverter.Convert(value, targetInfo.PropertyType, ValueConverterParameter); } else { value = GetConvertedValue(value, targetType.IsArray ? targetType.GetElementType() : targetInfo.PropertyType); } if (targetType.IsArray) { ((Array)targetObject).SetValue(value, targetIndices.Last().Cast <int>().ToArray()); } else { targetInfo.SetValue(targetObject, value, targetIndices.Last()); } }
private void ResultsAvailable() { _viewModel.ResultsAvailable -= ResultsAvailable; _syncContext?.Post(o => ResultPaneRow.Height = new GridLength(1, GridUnitType.Star), null); }
public void OnCompleted(Action continuation) => _syncContext.Post(SynchronizationContextAwaiter.PostCallback, continuation);
void HandleElapsed(object?state) { _context?.Post((o) => Fire?.Invoke(), null); }
public void BeginInvokeOnMainThread(Action action) { s_context.Post((o) => action(), null); }
private void OnGetResponse(IAsyncResult asyncResult) { byte[] imageBuffer = new byte[1024 * 1024]; // get the response HttpWebRequest req = (HttpWebRequest)asyncResult.AsyncState; try { HttpWebResponse resp = (HttpWebResponse)req.EndGetResponse(asyncResult); // find our magic boundary value string contentType = resp.Headers["Content-Type"]; if (!string.IsNullOrEmpty(contentType) && !contentType.Contains("=")) { throw new Exception("Invalid content-type header. The camera is likely not returning a proper MJPEG stream."); } string boundary = resp.Headers["Content-Type"].Split('=')[1].Replace("\"", ""); byte[] boundaryBytes = Encoding.UTF8.GetBytes(boundary.StartsWith("--") ? boundary : "--" + boundary); Stream s = resp.GetResponseStream(); BinaryReader br = new BinaryReader(s); _streamActive = true; byte[] buff = br.ReadBytes(ChunkSize); while (_streamActive) { // find the JPEG header int imageStart = buff.Find(JpegHeader); if (imageStart != -1) { // copy the start of the JPEG image to the imageBuffer int size = buff.Length - imageStart; Array.Copy(buff, imageStart, imageBuffer, 0, size); while (true) { buff = br.ReadBytes(ChunkSize); // find the boundary text int imageEnd = buff.Find(boundaryBytes); if (imageEnd != -1) { // copy the remainder of the JPEG to the imageBuffer Array.Copy(buff, 0, imageBuffer, size, imageEnd); size += imageEnd; byte[] frame = new byte[size]; Array.Copy(imageBuffer, 0, frame, 0, size); ProcessFrame(frame); // copy the leftover data to the start Array.Copy(buff, imageEnd, buff, 0, buff.Length - imageEnd); // fill the remainder of the buffer with new data and start over byte[] temp = br.ReadBytes(imageEnd); Array.Copy(temp, 0, buff, buff.Length - imageEnd, temp.Length); break; } // copy all of the data to the imageBuffer Array.Copy(buff, 0, imageBuffer, size, buff.Length); size += buff.Length; } } } #if WINRT resp.Dispose(); #else resp.Close(); #endif } catch (Exception ex) { #if WINRT if (Error != null) { _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Error(this, new ErrorEventArgs() { Message = ex.Message, ErrorCode = ex.HResult })); } #else if (Error != null) { _context?.Post(delegate { Error(this, new ErrorEventArgs() { Message = ex.Message }); }, null); } #endif return; } }