public MainViewModel(ITypographService serivce, ISettings settings) { _service = serivce; Settings = settings; _dispatcher = Dispatcher.CurrentDispatcher; ShowSettingsFlyout = new RelayCommand(() => { _dispatcher.Invoke(() => IsSettingsFlyoutOpen = true); }); Typographify = new RelayCommand(() => { _dispatcher.Invoke(() => IsWorking = true); _service.Typographify(Text, (result, error) => { if (error != null) _HandleException(error); if (result != null) _dispatcher.Invoke(() => Text = result); _dispatcher.Invoke(() => IsWorking = false); }); } , () => !string.IsNullOrWhiteSpace(Text) && !IsWorking); }
public ErrorHighlighter(IWpfTextView view, ITextDocument document, IVsTaskList tasks, DTE2 dte) { _view = view; _document = document; _text = new Adornment(); _tasks = tasks; _dispatcher = Dispatcher.CurrentDispatcher; _adornmentLayer = view.GetAdornmentLayer(ErrorHighlighterFactory.LayerName); _view.ViewportHeightChanged += SetAdornmentLocation; _view.ViewportWidthChanged += SetAdornmentLocation; _text.MouseUp += (s, e) => { dte.ExecuteCommand("View.ErrorList"); }; _timer = new Timer(750); _timer.Elapsed += (s, e) => { _timer.Stop(); Task.Run(() => { _dispatcher.Invoke(new Action(() => { Update(false); }), DispatcherPriority.ApplicationIdle, null); }); }; _timer.Start(); }
public void StartSplashScreen() { if (_thread == null) { _thread = new Thread(StartSplashScreen); _thread.SetApartmentState(ApartmentState.STA); _thread.Start(); return; } if (_dispatcher == null) { _dispatcher = Dispatcher.CurrentDispatcher; _dispatcher.Invoke(new Action(() => { SplashScreen = new DevExSplashScreen(); SplashScreen.SetProgressState(true); SplashScreen.ShowDialog(); })); while (!_dispatcher.HasShutdownStarted) { _dispatcher.Invoke(new Action(() => { }), DispatcherPriority.SystemIdle); } } }
/// <summary> /// Creates a square image and attaches an event handler to the layout changed event that /// adds the the square in the upper right-hand corner of the TextView via the adornment layer /// </summary> /// <param name="view">The <see cref="IWpfTextView"/> upon which the adornment will be drawn</param> /// <param name="imageProvider">The <see cref="IImageProvider"/> which provides bitmaps to draw</param> /// <param name="setting">The <see cref="Setting"/> contains user image preferences</param> public ClaudiaIDE(IWpfTextView view, IImageProvider imageProvider, Setting setting) { try { _dispacher = Dispatcher.CurrentDispatcher; _imageProvider = imageProvider; _view = view; _positionHorizon = setting.PositionHorizon; _positionVertical = setting.PositionVertical; _imageOpacity = setting.Opacity; _fadeTime = setting.ImageFadeAnimationInterval; _image = new Image { Opacity = setting.Opacity, IsHitTestVisible = false }; _adornmentLayer = view.GetAdornmentLayer("ClaudiaIDE"); _view.ViewportHeightChanged += delegate { RepositionImage(); }; _view.ViewportWidthChanged += delegate { RepositionImage(); }; _view.ViewportLeftChanged += delegate { RepositionImage(); }; _imageProvider.NewImageAvaliable += delegate { _dispacher.Invoke(ChangeImage); }; ChangeImage(); } catch (Exception) { } }
public RoslynCodeAnalysisHelper(IWpfTextView view, ITextDocument document, IVsTaskList tasks, DTE2 dte, SVsServiceProvider serviceProvider, IVsActivityLog log) { _view = view; _document = document; _text = new Adornment(); _tasks = tasks; _serviceProvider = serviceProvider; _log = log; _dispatcher = Dispatcher.CurrentDispatcher; _adornmentLayer = view.GetAdornmentLayer(RoslynCodeAnalysisFactory.LayerName); _view.ViewportHeightChanged += SetAdornmentLocation; _view.ViewportWidthChanged += SetAdornmentLocation; _text.MouseUp += (s, e) => dte.ExecuteCommand("View.ErrorList"); _timer = new Timer(750); _timer.Elapsed += (s, e) => { _timer.Stop(); System.Threading.Tasks.Task.Run(() => { _dispatcher.Invoke(new Action(() => Update(false)), DispatcherPriority.ApplicationIdle, null); }); }; _timer.Start(); }
public void UpdateTagsCollection(string tagDisplayName, string tagValue, Dispatcher dispatcher) { bool tagFound = false; dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate() { foreach (TagInfo summarySignal in _summaryStatusTags) { if (summarySignal.TagName.Equals(tagDisplayName)) { int index = _summaryStatusTags.IndexOf(summarySignal); _summaryStatusTags.RemoveAt(index); summarySignal.TagName = tagDisplayName; summarySignal.TagValue = tagValue; _summaryStatusTags.Insert(index, summarySignal); tagFound = true; break; } } if (!tagFound) { TagInfo summarySignal = new TagInfo(); summarySignal.TagValue = tagValue; summarySignal.TagName = tagDisplayName; _summaryStatusTags.Add(summarySignal); } })); }
private static void GuardUiaServerInvocation(Action invocation, Dispatcher dispatcher) { if (dispatcher == null) throw new ElementNotAvailableException(); Exception remoteException = null; bool completed = false; dispatcher.Invoke(DispatcherPriority.Send, TimeSpan.FromMinutes(3.0), (Action)(() => { try { invocation(); } catch (Exception e) { remoteException = e; } catch { remoteException = null; } finally { completed = true; } })); if (completed) { if (remoteException != null) throw remoteException; } else if (dispatcher.HasShutdownStarted) throw new InvalidOperationException("AutomationDispatcherShutdown"); else throw new TimeoutException("AutomationTimeout"); }
public void UpdateTagsCollection(string tagDisplayName, string tagValue, Dispatcher dispatcher) { bool tagFound = false; dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate() { foreach (TagInfo estop in _estopTags) { if (estop.TagName.Equals(tagDisplayName)) { int index = _estopTags.IndexOf(estop); _estopTags.RemoveAt(index); estop.TagName = tagDisplayName; estop.TagValue = tagValue; _estopTags.Insert(index, estop); tagFound = true; break; } } if (!tagFound) { TagInfo estop = new TagInfo(); estop.TagValue = tagValue; estop.TagName = tagDisplayName; _estopTags.Add(estop); } })); }
public StatisticsViewModel(Statistics statistics) { _statistics = statistics; StatisticsList = new ObservableCollection<string>(); _dispatcher = Dispatcher.CurrentDispatcher; _timer = new Timer(s => _dispatcher.Invoke((Action)(Update)), null, TimeSpan.Zero, TimeSpan.FromMilliseconds(250)); }
private TelemetryData(int udpPort, Dispatcher dispatcher) { _dispatcher = dispatcher; _dispatcher.Invoke(() => Status = "Starting"); _udpReceiver = new UdpReceiver(udpPort); Debug.WriteLine("Starting telemetry receiver on port " + udpPort); _lastReceiveTime = DateTime.Now; }
public static BitmapSource ConvertBitmapToImageSourceOnDispatcher(Bitmap bitmap, Dispatcher dispatcher) { BitmapSource source = null; Action<object> dispatcherDelegate = x => { source = ConvertBitmapToImageSource(x as Bitmap); }; dispatcher.Invoke(dispatcherDelegate, bitmap); return source; }
public DeckList(string path, Dispatcher disp, DeckList parent = null, bool isRoot = false) { Parent = parent; Path = path; Name = new DirectoryInfo(path).Name; if (isRoot) IsRootFolder = true; DeckLists = new ObservableCollection<DeckList>(); Decks = new ObservableCollection<MetaDeck>(); foreach (var f in Directory.GetDirectories(path).Select(x => new DirectoryInfo(x))) { if (isRoot) { if (DataNew .DbContext.Get() .Games .Any(x => x.Name.Equals(f.Name, StringComparison.InvariantCultureIgnoreCase))) { var dl = new DeckList(f.FullName, disp, this); dl.IsGameFolder = true; disp.Invoke(new Action(() => DeckLists.Add(dl))); } } else { var dl = new DeckList(f.FullName, disp, this); disp.Invoke(new Action(() => DeckLists.Add(dl))); } } foreach (var f in Directory.GetFiles(Path, "*.o8d")) { var deck = new MetaDeck(f); disp.Invoke(new Action(() => Decks.Add(deck))); } foreach (var d in DeckLists.SelectMany(x => x.Decks)) { MetaDeck d1 = d; disp.Invoke(new Action(() => Decks.Add(d1))); } }
public static IProgressDialog CreateProgressDialog( IDialogHost dialogHost, DialogMode dialogMode, Dispatcher dispatcher) { IProgressDialog dialog = null; dispatcher.Invoke( new Action(() => dialog = new WaitProgressDialog( dialogHost, dialogMode, false, dispatcher)), DispatcherPriority.DataBind); return dialog; }
public static void OnUiThreadSync(Action action, Dispatcher disp = null, DispatcherPriority prio = DispatcherPriority.Background) { if (disp == null) { if (Application.Current != null) disp = Application.Current.Dispatcher; } if (disp != null) disp.Invoke(action, prio); }
public FilteredHttpsProtocol(Dispatcher dispatcher, IUrlFilter urlFilter) { ArgumentUtility.CheckNotNull ("dispatcher", dispatcher); ArgumentUtility.CheckNotNull ("urlFilter", urlFilter); _urlFilter = urlFilter; _dispatcher = dispatcher; _dispatcher.Invoke ( () => { var originalHandler = new HttpsProtocol(); _wrapped = (IInternetProtocol) originalHandler; }); }
public void Start(int bpm, Dispatcher dispatcher) { IsRunning = true; _timer = new Timer(); // bpm to ms delay _timer.Interval = 60000.0 / bpm; _timer.Elapsed += delegate { dispatcher.Invoke((Action)(() => { _sample.Play(false); })); }; _timer.Start(); }
public void GetBitmapSource(Dispatcher dispatcher, Action<BitmapSource> BitmapSourceCallback) { if (dispatcher == null) throw new ArgumentNullException("dispatcher"); if (BitmapSourceCallback == null) throw new ArgumentNullException("BitmapSourceCallback"); dispatcher.Invoke((Action)delegate { BitmapSource bitmap = BitmapSource.Create(XRes, YRes, 96, 96, Format, null, Map, Stride); BitmapSourceCallback(bitmap); }); }
internal static void SaveToDisk(Item item, Dispatcher dispatcher) { try { createSaveFolder(); SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.InitialDirectory = string.Format("{0}\\{1}", Environment.CurrentDirectory, SAVE_LOCATION); saveDialog.FileName = string.Format("{0} - {1}.png", item.Name, DateTime.Now.ToString("dd-MM-yyyy-HH-mm-ss")); saveDialog.Filter = "png files (*.png)|*.png|All files (*.*)|*.*"; saveDialog.FilterIndex = 2; saveDialog.RestoreDirectory = true; var result = saveDialog.ShowDialog(); if (!result.HasValue || !result.Value) return; var itemHover = new ItemHoverImage() { DataContext = ItemHoverViewModelFactory.Create(item) }; itemHover.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); itemHover.Arrange(new Rect(itemHover.DesiredSize)); dispatcher.Invoke(DispatcherPriority.Loaded, new Action(() => { })); RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)(itemHover.ActualWidth * 1.24), (int)(itemHover.ActualHeight * 1.24), 120, 120, PixelFormats.Pbgra32); renderTarget.Render(itemHover); BitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(renderTarget)); createSaveFolder(); using (var fileStream = File.OpenWrite(saveDialog.FileName)) { encoder.Save(fileStream); } MessageBox.Show("Image saved", item.Name + " saved", MessageBoxButton.OK, MessageBoxImage.Information); } catch (Exception ex) { Logger.Log("Unable to save hover-image to disk : " + ex.ToString()); MessageBox.Show("Error saving image, error logged to DebugInfo.log", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
/// <summary> /// Creates a new instance of <see cref="SingleThreadedVideoEncoderWrapper"/>. /// </summary> /// <param name="encoderFactory"> /// Factory for creating an encoder instance. /// It will be invoked on the same thread as all subsequent operations of the <see cref="IVideoEncoder"/> interface. /// </param> public SingleThreadedVideoEncoderWrapper(Func<IVideoEncoder> encoderFactory) { Contract.Requires(encoderFactory != null); this.thread = new Thread(RunDispatcher) { IsBackground = true, Name = typeof(SingleThreadedVideoEncoderWrapper).Name }; var dispatcherCreated = new AutoResetEvent(false); thread.Start(dispatcherCreated); dispatcherCreated.WaitOne(); this.dispatcher = Dispatcher.FromThread(thread); // TODO: Create encoder on the first frame this.encoder = (IVideoEncoder)dispatcher.Invoke(encoderFactory); if (encoder == null) throw new InvalidOperationException("Encoder factory has created no instance."); }
public void LoadClasses(Dispatcher dispatcher) { var problemSolvers = new List<ProblemViewModel>(); Type solvableType = typeof (ISolvable); var solvables = Assembly.GetExecutingAssembly().GetTypes().Where(solvableType.IsAssignableFrom); foreach (var solvable in solvables.Where(s => !s.IsInterface)) { var instance = (ISolvable) Activator.CreateInstance(solvable); problemSolvers.Add(new ProblemViewModel(instance, dispatcher)); } dispatcher.Invoke(() => { foreach (var ps in problemSolvers.OrderBy(ps => ps.ProblemNumber)) { _problemSolvers.Add(ps); } }); }
public static EventHandler<ProgressChangedEventArgs> CreateHandler(Dispatcher dispatcher, FrameworkElement progressBar, Func<bool> cancelled, Action<double> onDispatcherInvoke) { DateTime lastUpdate = DateTime.MinValue; return new EventHandler<ProgressChangedEventArgs>((sender, e) => { if (DateTime.Now.Subtract(lastUpdate) < UpdateInterval && e.Progress != 1) { return; } lastUpdate = DateTime.Now; dispatcher.Invoke(new Action(() => { UpdateProgressValue(progressBar, e.Progress); onDispatcherInvoke(e.Progress); })); e.Cancel = cancelled(); }); }
public MainWindowViewModel() { RenderCommand = new RelayCommand<string>(StartRender); _dispatcher = Dispatcher.CurrentDispatcher; _worker.DoWork += (sender, args) => { var numberOfTicksStart = Environment.TickCount; var buffer = new uint[Width * Height]; var engine = new NaiveEngine(ref buffer, Width, Height); engine.Scene.InitScene(); engine.InitRender(); while (!engine.Render()) { _dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => RefreshImage(buffer, Environment.TickCount - numberOfTicksStart))); } }; }
public static MessageBoxResult Show(Dispatcher parent, string title, MessageBoxButton buttons, MessageBoxImage image, MessageBoxResult defaultButton, string message, params object[] args) { var formattedMessage = args == null || args.Length == 0 ? message : string.Format(CultureInfo.CurrentCulture, message, args); var options = CultureInfo.CurrentCulture.TextInfo.IsRightToLeft ? MessageBoxOptions.RightAlign | MessageBoxOptions.RtlReading : 0; Window window = null; var result = parent.Invoke( DispatcherPriority.Normal, new Func<MessageBoxResult>(delegate { if (window == null) { window = Application.Current.MainWindow; //return MessageBox.Show(formattedMessage, title, buttons, image, defaultButton, options); } return MessageBox.Show(window, formattedMessage, title, buttons, image, defaultButton, options); })); return (MessageBoxResult)result; }
public WindowDelegate(NavigationWindow window) { _window = window; _dispatcher = window.Dispatcher; _scenes = new List<Scene>(); _resources = new Dictionary<string, ResourceDictionary>(); _sceneIndex = -1; _windowRect = new Rect(); _dispatcher.Invoke(() => { _windowTopmost = window.Topmost; _windowState = window.WindowState; _windowStyle = window.WindowStyle; _windowResizemode = window.ResizeMode; _windowRect.X = window.Left; _windowRect.Y = window.Top; _windowRect.Width = window.Width; _windowRect.Height = window.Height; window.LoadCompleted += (sender, e) => NavigateFinished(); }); }
public void Invoke(object arg, params object[] args) { EventHandler method = null; EventHandler handler2 = null; object target = this.Target; System.Windows.Threading.Dispatcher dispatcher = this.Dispatcher; if (!this.IsDisposable) { if (this.IsDispatcherThreadAlive) { if (method == null) { method = delegate(object sender, EventArgs e) { this.handlerInfo.Invoke(target, new object[] { arg, e }); }; } dispatcher.Invoke(DispatcherPriority.Send, method, arg, args); } else if (target is DispatcherObject) { if (handler2 == null) { handler2 = delegate(object sender, EventArgs e) { this.handlerInfo.Invoke(target, new object[] { arg, e }); }; } dispatcher.BeginInvoke(DispatcherPriority.Send, handler2, arg, args); } else { ArrayList list = new ArrayList(); list.Add(arg); list.AddRange(args); this.handlerInfo.Invoke(target, list.ToArray()); } } }
public DispatcherConsumer(Dispatcher dispatcher, TimeSpan minTimeSpan) { _dispatcher = dispatcher; _minTimeSpan = HiResTimer.FromTimeSpan(minTimeSpan); _timer = new Timer(state => { _nextQuantumTime = HiResTimer.Now() + _minTimeSpan; // prepare batch (generate lots of RunOnDispatcher notifications) _runOnDispatcher = new List<Action>(); // TODO: race condition where this is null at X, need to prevent timers colliding? Refresh(); // obtain dispatcher actions List<Action> actions; using (this.Lock()) { actions = _runOnDispatcher; _runOnDispatcher = null; } // execute batch on dispatcher if (actions != null && actions.Count > 0) // X { if (_dispatcher.CheckAccess()) actions.ForEach(); else _dispatcher.Invoke(new Action(() => actions.ForEach()), DispatcherPriority.DataBind); } }); _runOnRefresh.OnNotify = () => { // see if this is too short a time since last quantum? var wait = Math.Max(0, _nextQuantumTime - HiResTimer.Now()); _timer.Change(HiResTimer.ToTimeSpan(wait), TimeSpan.FromMilliseconds(-1)); }; }
public static void Show(Bitmap expected, Bitmap actual) { using (var startedEvent = new ManualResetEventSlim(initialState: false)) { System.Windows.Threading.Dispatcher dispatcher = null; var uiThread = new Thread(() => { // Create and install a new dispatcher context SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(Dispatcher.CurrentDispatcher)); dispatcher = Dispatcher.CurrentDispatcher; // Signal that it is initialized // ReSharper disable once AccessToDisposedClosure startedEvent.Set(); // Start the dispatcher processing Dispatcher.Run(); }); // Set the apartment state uiThread.SetApartmentState(ApartmentState.STA); // Make the thread a background thread uiThread.IsBackground = true; // Start the thread uiThread.Start(); startedEvent.Wait(); dispatcher.Invoke(() => { var window = new ImageDiffWindow(expected, actual); window.ShowDialog().IgnoreReturnValue(); }); dispatcher.InvokeShutdown(); uiThread.Join(1000).IgnoreReturnValue(); } }
public void run_application() { var waitForApplicationStart = new ManualResetEvent(false); var thread = new Thread(() => { _app = new App(); _app.Startup += (s, e) => { waitForApplicationStart.Set(); }; _app.Run(); }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); waitForApplicationStart.WaitOne(); _dispatcher = Dispatcher.FromThread(thread); _dispatcher.Invoke(new ThreadStart(() => _window = _app.MainWindow as TestApp.Window)); _whiteApp = Application.Attach(Process.GetCurrentProcess()); _windowAutomation = _whiteApp.GetWindow("MainWindow"); }
/// <summary> /// Starts a new delay execution. /// The previous waiting can be canceled. /// </summary> /// <param name="action">The action to execute with delay.</param> /// <param name="delayTime">Time to wait before executing the action.</param> public void Start(Action action, TimeSpan delayTime) { if (action == null) { throw new ArgumentNullException(nameof(action)); } if (IsInDispatcherThread()) { StartImpl(action, delayTime); } else { #if NICENIS_UWP TheWindow.Current.Dispatcher.RunAsync(_delegatePriority, () => StartImpl(action, delayTime)).GetResults(); #else _dispatcher.Invoke(() => StartImpl(action, delayTime), _delegatePriority); #endif } }
/// <summary> /// Invokes action on the thread of the current WPF application dispatcher. /// </summary> /// <param name="action">Action to execute</param> public void Invoke(Action action) { dispatcher.Invoke(action); }
public ContactWatcherSingular(Dispatcher dispatcher, ContactLoader loader, string directory, ContactTypes type, ContactWatcherEventCallback callback) { Assert.IsNotNull(dispatcher); // It's expected that this is created on the same thread as the manager, // so don't need to go through the dispatcher for methods invoked in the constructor. Assert.IsTrue(dispatcher.CheckAccess()); Assert.IsNotNull(loader); Assert.IsFalse(string.IsNullOrEmpty(directory)); Assert.IsNotNull(callback); Assert.IsTrue(Enum.IsDefined(typeof(ContactTypes), type)); Assert.AreNotEqual(ContactTypes.All, type); Assert.AreNotEqual(ContactTypes.None, type); _dispatcher = dispatcher; _rootDirectory = directory; _loader = loader; _notify = callback; _findExtension = "*" + Contact.GetExtensionsFromType(type); // This is why creating this object is expensive: // In order to be able to give accurate change notifications we need to know all the contacts that are present at the beginning. _knownContacts = new Dictionary<string, ContactInfo>(); // _pushedFrames = 0; _frame = new DispatcherFrame { Continue = false }; // Create the timer, but only signal it if we're going to need to reprocess an update. _timer = new Timer(); _timer.Tick += delegate { if (!_stopProcessing) { // Not invoked by the FileSystemWatcher, so don't push a frame here. _dispatcher.Invoke(DispatcherPriority.Background, (ThreadStart)_ReprocessPendingUpdate); } }; _timer.Interval = TimeSpan.FromMilliseconds(_TimerMsDelay); _timer.IsEnabled = false; _PopulateKnownContacts(type); _fileWatch = new FileSystemWatcher(_rootDirectory, _findExtension) { IncludeSubdirectories = true, NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.Attributes, }; // There's some extra indirection required here because the manager requires thread affinity. _fileWatch.Changed += FileSystemWatcher_OnChanged; _fileWatch.Created += FileSystemWatcher_OnCreated; _fileWatch.Deleted += FileSystemWatcher_OnDeleted; _fileWatch.Renamed += FileSystemWatcher_OnRenamed; _fileWatch.EnableRaisingEvents = true; }
public static void Invoke <T1, T2, T3, T4>(this Dispatcher d, Action <T1, T2, T3, T4> action, T1 arg1, T2 arg2, T3 arg3, T4 arg4) { d.Invoke(action, arg1, arg2, arg3, arg4); }
public static void Invoke <T1, T2>(this Dispatcher d, Action <T1, T2> action, T1 arg1, T2 arg2) { d.Invoke(action, arg1, arg2); }
public static void Invoke <T>(this Dispatcher d, Action <T> action, T arg1) { d.Invoke(action, arg1); }
public static void Invoke(this Dispatcher d, Action action) { d.Invoke(action); }
private void theTimer_Elapsed(object sender, ElapsedEventArgs e) { double movingStep; if (ext.ActionsList.Count != 0) { CarAction carAction = ext.ActionsList[0]; if (carAction.Duration > 0) { Action action = null; double num = RandomMersene.genrand_real1() * ((RandomMersene.genrand_bool() ? -1.0 : 1.0)); if (carAction.MoveAction == MoveAction.SmartMovement) { action = () => this.theCar.translateRotateCuplu(); carAction.Duration -= this.theTimer.Interval / 1000; } else if (carAction.Direction != Direction.Straight) { movingStep = (double)((carAction.MoveAction == MoveAction.Forward ? 1 : -1)) * ext.MovingStep + num * ext.deviationPercent / 100 * ext.MovingStep; action = () => this.theCar.autoTranslateRotate(movingStep, carAction.Direction); carAction.Duration = carAction.Duration - this.theTimer.Interval / 1000; } else { movingStep = (double)((carAction.MoveAction == MoveAction.Forward ? 1 : -1)) * ext.MovingStep + num * ext.deviationPercent / 100 * ext.MovingStep; action = () => this.theCar.Move(movingStep); carAction.Duration = carAction.Duration - this.theTimer.Interval / 1000; } System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; if (action != null) { Action action1 = () => { if (action != null) { action(); } this.RefreshShits(); }; if (!dispatcher.CheckAccess()) { try { dispatcher.Invoke(action1); } catch { } } else { action1(); } } } else { ext.ActionsList.Remove(carAction); } } if (tmpRefreshShitsTimes > 0) { Action action1 = () => { this.theCar.autoTranslateRotate(0, Direction.Left); this.RefreshShits(); }; System.Windows.Threading.Dispatcher dispatcher = base.Dispatcher; if (!dispatcher.CheckAccess()) { try { dispatcher.Invoke(action1); } catch { } } else { action1(); } tmpRefreshShitsTimes--; } }
private void LoadAndSetup(CfgSettings Config) { //NetworkReader nr = new NetworkReader(); //nr.OnDataRevieved += NrOnOnDataRevieved; dsc = this.Dispatcher; if (_logProcessor.InitSocket(Config, _agentDataDictionary, dsc, _currentAgent)) { try { Item.cfgSettings = Config; this.Title = "MultiAgentz Visualization - " + Config.Host + ":" + Config.Port; StatusLabel.Foreground = new SolidColorBrush(Colors.Black); StatusLabel.Content = _currentMessage; MainSlider.Maximum = 10; LineNumberToCoordinateConverter.FieldCount = (int) MainSlider.Maximum; LineNumberToCoordinateConverter.FieldDuration = 100; MainSlider.Value = 0; int number = (int) MainSlider.Maximum; dsc.Invoke(() => { SliderMark10.Content = number; { SliderMark1.Content = (int) (number/10); SliderMark2.Content = (int) (number*2/10); SliderMark3.Content = (int) (number*3/10); SliderMark4.Content = (int) (number*4/10); SliderMark5.Content = (int) (number*5/10); SliderMark6.Content = (int) (number*6/10); SliderMark7.Content = (int) (number*7/10); SliderMark8.Content = (int) (number*8/10); SliderMark9.Content = (int) (number*9/10); } }); // UpdateSliderMarks(dsc, (int)MainSlider.Maximum); AuctionsLabel.Header = AgentDataDictionary.GetSpecialItemGroupName(); } catch { System.Windows.MessageBox.Show("Something wrong with configuration file content"); } } else { System.Windows.MessageBox.Show("Cannot coonnect to host: " + Config.Host + ":" + Config.Port); } }
public static void Refresh(Dispatcher dispatcher) { dispatcher.Invoke(new Action(() => CommandManager.InvalidateRequerySuggested())); }
public static void Sync(this Disp dispatcher, Action action) => dispatcher.Invoke(action, Empty <object>());
public static TResult Sync <TResult>(this Disp dispatcher, Func <TResult> action) => (TResult)dispatcher.Invoke(action, Empty <object>());
/// <summary> /// This procedure changes the current WPF Application Theme into another theme /// while the application is running (re-boot should not be required). /// </summary> /// <param name="s"></param> /// <param name="e"></param> /// <param name="disp"></param> private void ChangeThemeCmd_Executed(object s, ExecutedRoutedEventArgs e, System.Windows.Threading.Dispatcher disp) { string oldTheme = ThemesManager.DefaultThemeName; try { if (e == null) { return; } if (e.Parameter == null) { return; } string newThemeName = e.Parameter as string; // Check if request is available if (newThemeName == null) { return; } oldTheme = this.mSettingsManager.SettingData.CurrentTheme; // The Work to perform on another thread ThreadStart start = delegate { // This works in the UI tread using the dispatcher with highest Priority disp.Invoke(DispatcherPriority.Send, (Action)(() => { try { if (this.mThemesManager.SetSelectedTheme(newThemeName) == true) { this.mSettingsManager.SettingData.CurrentTheme = newThemeName; this.ResetTheme(); // Initialize theme in process } } catch (Exception exp) { logger.Error(exp.Message, exp); _MsgBox.Show(exp, Edi.Util.Local.Strings.STR_MSG_IssueTrackerTitle, MsgBoxButtons.OK, MsgBoxImage.Error, MsgBoxResult.NoDefaultButton, this.mAppCore.IssueTrackerLink, this.mAppCore.IssueTrackerLink, Edi.Util.Local.Strings.STR_MSG_IssueTrackerText, null, true); } })); }; // Create the thread and kick it started! Thread thread = new Thread(start); thread.Start(); } catch (Exception exp) { this.mSettingsManager.SettingData.CurrentTheme = oldTheme; logger.Error(exp.Message, exp); _MsgBox.Show(exp, Edi.Util.Local.Strings.STR_MSG_IssueTrackerTitle, MsgBoxButtons.OK, MsgBoxImage.Error, MsgBoxResult.NoDefaultButton, this.mAppCore.IssueTrackerLink, this.mAppCore.IssueTrackerLink, Edi.Util.Local.Strings.STR_MSG_IssueTrackerText, null, true); } }
public static void DoEvents(Dispatcher dis) { dis.Invoke(DispatcherPriority.Background, new Action(delegate{ })); }