Beispiel #1
0
        public TaskContext Execute(ITask task, object associatedData = null)
        {
            var context = new TaskContext(task, associatedData);

            _dispatcher.BeginInvoke(() =>
            {
                _all.Add(task);
                _contexts.Add(context);
                UpdateBusy();
            });


            task.Execute(context).ContinueWith((p, d) =>
            {
                _dispatcher.BeginInvoke(() =>
                {
                    _all.Remove(task);
                    _contexts.Remove(context);
                    UpdateBusy();
                });
            }).Failed((p, d) =>
            {
            });

            return(context);
        }
        private void OnFrameCompleted()
        {
#if TIMING
            GameBoy._swBeginInvoke.Start();
            _dispatcher.BeginInvoke(new Action(UpdateFromGameboy), null);
            GameBoy._swBeginInvoke.Stop();
#else
            _dispatcher.BeginInvoke(new Action(UpdateFromGameboy), null);
#endif
        }
Beispiel #3
0
 /// <summary>
 /// Called when [track progress].
 /// </summary>
 /// <param name="trackProgressEvent">The track progress event.</param>
 private void OnTrackProgress(TrackProgressEvent trackProgressEvent)
 {
     dispatcher.BeginInvoke(new Action <TrackProgressEvent>(a =>
     {
         var pos = TimeSpan.FromMilliseconds(a.Position);
         CurrentPositionString = GetTimeString(pos);
         if (hasSought)
         {
             return;
         }
         currentPosition = a.Position; // Don't set CurrentPosition directly as it will seek as well
         RaisePropertyChanged(() => CurrentPosition);
     }), trackProgressEvent);
 }
        private void Run()
        {
            try {
                Thread.Sleep(_delay);

                if (Application.Current == null)
                {
                    return;
                }
                lock (_dispatcherOperationLock) _dispatcherOperation = _dispatcher.BeginInvoke(_action);
            }
            catch (ThreadAbortException ex) {
                Exception = ex;
            }
            catch (ThreadInterruptedException ex) {
                Exception = ex;
            }
            catch (Exception ex) {
                Exception = ex;
            }
            finally {
                lock (this) {
                    IsCompleted = true;
                    if (_asyncWaitHandle != null)
                    {
                        ((ManualResetEvent)_asyncWaitHandle).Set();
                    }
                }
            }
        }
Beispiel #5
0
 private void SafeNotify(Action method, bool post)
 {
     try
     {
         // Fire the event on the UI thread
         if (post)
         {
             if (Dispatcher.CheckAccess())
             {
                 method();
             }
             else
             {
                 Dispatcher.BeginInvoke(method);
             }
         }
         // Fire event on a ThreadPool thread
         else
         {
             ThreadPool.QueueUserWorkItem(o => method(), null);
         }
     }
     catch (Exception ex)
     {
         // If there's an exception write it to the Output window
         Debug.WriteLine(ex.ToString());
     }
 }
        private void UpdatePlugins()
        {
            try
            {
                _updatePluginsCommand.CanBeExecuted = false;

                var repositories      = _applicationSettings.AutoUpdate.PluginRepositories;
                var numUpdatedPlugins = _pluginUpdater.UpdatePluginsAsync(repositories);
                numUpdatedPlugins.ContinueWith(task => _dispatcher.BeginInvoke(() => OnPluginsUpdated(task)));
            }
            catch (Exception)
            {
                _updatePluginsCommand.CanBeExecuted = true;
                throw;
            }
        }
Beispiel #7
0
        protected void RaiseCollectionReset()
        {
            var copy = CollectionChanged;

            if (copy != null)
            {
                if (!dispatcher.IsUIThread)
                {
                    dispatcher.BeginInvoke(RaiseCollectionReset);
                }
                else
                {
                    copy(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
                }
            }
        }
        private void ScanSnapshotsFolder()
        {
            var searchPattern = string.Format("*.{0}", Constants.SnapshotExtension);

            try
            {
                // Blocking the timer task is on purpose so we don't perform more scans than we actually can
                var files = _analysisStorage.EnumerateSnapshots().AwaitResult().ToList();
                _dispatcher.BeginInvoke(() => Synchronise(files));
            }
            catch (IOException e)
            {
                if (!_loggedIoException)
                {
                    Log.WarnFormat("Unable to enumerate snapshots: {0}", e.Message);
                    _loggedIoException = true;
                }
                else
                {
                    Log.DebugFormat("Unable to enumerate snapshots: {0}", e.Message);
                }
            }
            catch (Exception e)
            {
                Log.ErrorFormat("Caught unexpected exception: {0}", e);
            }
        }
Beispiel #9
0
 private void ProcessMessage(ESP esp, IDispatcher dispatcher)
 {
     if (!FoundEsps.Any(e => e.Ip.Equals(esp.Ip)))
     {
         dispatcher.BeginInvoke(() => FoundEsps.Add(esp));
     }
 }
            public override void OnInvoke(MethodInterceptionArgs args)
            {
                IDispatcherObject threadAffined = args.Instance as IDispatcherObject;
                IDispatcher       dispatcher    = threadAffined.Dispatcher;

                if (dispatcher == null)
                {
                    throw new InvalidOperationException("Cannot dispatch method: synchronization context is null");
                }


                if (this.isAsync)
                {
                    dispatcher.BeginInvoke(new WorkItem(args, true));
                }
                else if (dispatcher.CheckAccess())
                {
                    args.Proceed();
                }
                else
                {
                    WorkItemWithExceptionInterceptor workItem = new WorkItemWithExceptionInterceptor(args);
                    dispatcher.Invoke(workItem);

                    if (workItem.HasError)
                    {
                        throw new AggregateException("Exception has been thrown by the target of an invocation", workItem.Exception);
                    }
                }
            }
Beispiel #11
0
        private void OnInstallationFinished(Task task)
        {
            _dispatcher.BeginInvoke(() =>
            {
                string result;
                if (task.IsFaulted)
                {
                    result       = "failed";
                    HasFailed    = true;
                    ErrorMessage = FormatErrorMessage(task.Exception);
                }
                else
                {
                    _success = true;
                    result   = "succeeded";
                }

                _installationTask = null;

                InstallationResult = result;

                IsInstalling       = false;
                IsPostInstallation = true;

                _launchCommand.RaiseCanExecuteChanged();
            });
        }
Beispiel #12
0
        public void ShowError(Exception exception, IErrorContainer errorContainer)
        {
            if (exception == null)
            {
                return;
            }

            ErrorContainer errorGrid = (ErrorContainer)errorContainer;

            if (!_dispatcher.CheckAccess())
            {
                _dispatcher.BeginInvoke(() => ShowError(exception, errorGrid));
                return;
            }

            ErrorNotification errorNotification = new ErrorNotification();

            errorGrid.RowDefinitions.Add(new RowDefinition {
                Height = GridLength.Auto
            });
            errorNotification.SetValue(Grid.RowProperty, errorGrid.RowDefinitions.Count - 1);
            errorGrid.Children.Add(errorNotification);
            errorGrid.UpdateLayout(); // Force OnApplyTemplate for ErrorNotification

            errorNotification.Show(exception);
        }
Beispiel #13
0
        //    private NotifyCollectionChangedEventArgs eLast;
        // this is connected to the DispatherTimer
        private void TimerCallback(object state)
        {
            lock (_lock)
            {
//        trottlteNotification = false;
                // Fire the event on the UI thread
                if (Dispatcher.CheckAccess())
                {
#if TEST
                    logger.Debug("direct notification");
#endif
                    base.OnCollectionChanged(new System.Collections.Specialized.NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction.Reset));
                }
                else
                {
#if TEST
                    logger.Debug("dispatcher notification");
#endif
                    // base.
                    Dispatcher.BeginInvoke(() => base.OnCollectionChanged(new System.Collections.Specialized.NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction.Reset)));
                }
                if (this.onCountChange != null)
                {
                    this.onCountChange();
                }
            }
        }
Beispiel #14
0
        private async void Update()
        {
            IsUpdating = true;
            Percent    = 0;
            if (FileName != null)
            {
                var taskServer = httpsServer.Start(FileName, (percent) => dispatcher.BeginInvoke(() => Percent = percent));
                if (Rebuild)
                {
                    System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo()
                    {
                        UseShellExecute = true, WorkingDirectory = Path.GetDirectoryName(FileName)?.Replace("build", "")
                    };
                    info.FileName  = @"C:\Users\BorisMakovecki\.espressif\tools\idf-exe\1.0.1\idf.py.exe";
                    info.Arguments = "build";
                    System.Diagnostics.Process p = new System.Diagnostics.Process();

                    p.StartInfo = info;

                    p.Start();
                    //p.WaitForExit();
                    //string output = p.StandardOutput.ReadToEnd();
                }
                messageService.StartOTAUpdate(Path.GetFileName(FileName), httpsServer.Port, esp, $"http://192.168.1.2:{httpsServer.Port}/");//{System.Net.Dns.GetHostName()}
                await taskServer;
                Cancel();
            }
        }
 private void OnFrameCompleted()
 {
     if (Update)
     {
         _dispatcher.BeginInvoke(new Action(CopyFromDomain), null);
     }
 }
        public virtual void Publish <TEvent>(TEvent message, bool asynchronously) where TEvent : Event
        {
            var typeOfEvent = typeof(TEvent);

            Action action = () =>
            {
                lock (listenerLock)
                {
                    if (!listeners.ContainsKey(typeOfEvent))
                    {
                        return;
                    }

                    foreach (var listener in listeners[typeOfEvent])
                    {
                        var typedReference = (IListenTo <TEvent>)listener;
                        typedReference.Handle(message);
                    }
                }
            };

            if (asynchronously)
            {
                dispatcher.BeginInvoke(action);
            }
            else
            {
                action();
            }
        }
Beispiel #17
0
 /// <summary>
 /// Called when [track changed].
 /// </summary>
 /// <param name="trackChangedEvent">The track changed event.</param>
 private void OnTrackChanged(TrackChangedEvent trackChangedEvent)
 {
     dispatcher.BeginInvoke(new Action(() =>
     {
         if (null != playingFile)
         {
             playingFile.IsPlaying = false;
         }
         SelectedFile = Files.Find(x => x.File == trackChangedEvent.File);
         playingFile  = SelectedFile;
         if (null == playingFile)
         {
             return;
         }
         playingFile.IsPlaying = true;
     }));
 }
Beispiel #18
0
 private void OnFrameCompleted()
 {
     if (Update)
     {
         _dispatcher.BeginInvoke(new Action(CopyFromDomain), null);
         _currentFrame = (_currentFrame + 1) % _numberOfFramesPerImage;
     }
 }
Beispiel #19
0
        protected TimerBase(string name, int timeout, IDispatcher dispatcher)
        {
            Dispatcher = dispatcher;
            Name = name;
            TimeOut = timeout;
            timer = new Timer(state => Dispatcher.BeginInvoke(DoTick), this, Timeout.Infinite, Timeout.Infinite);

        }
 protected virtual void OnCurrentProfileChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
 {
     _dispatcher?.BeginInvoke(() =>
     {
         CurrentProfileChanged?.Invoke(this, EventArgs.Empty);
         RaisePropertyChanged(nameof(CurrentProfile));
     });
 }
Beispiel #21
0
        private bool ProgressSearchCallback(float progress)
        {
            _dispatcher.BeginInvoke(() =>
            {
                Progress = (int)progress;
            });

            return(false);
        }
Beispiel #22
0
        /// <summary>Raises the <see cref="ObservableCollection&lt;FileView&gt;.CollectionChanged"/> event.</summary>
        /// <param name="e">The <see cref="System.Collections.Specialized.NotifyCollectionChangedEventArgs"/> instance containing the event data.</param>
        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            if (!_dispatcher.CheckAccess())
            {
                _dispatcher.BeginInvoke(() => OnCollectionChanged(e));
                return;
            }

            base.OnCollectionChanged(e);
        }
        public void RaisePropertyChanged([CallerMemberName] String propertyName = null)
        {
            if (Dispatcher == null)
            {
                return;
            }

            Dispatcher.BeginInvoke(() =>
                                   PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)));
        }
 /// <summary>
 /// Execute an action on the UI thread.
 /// </summary>
 /// <param name="action"></param>
 public static void Execute(Action action)
 {
     if (_dispatcher.CheckAccess())
     {
         action();
     }
     else
     {
         _dispatcher.BeginInvoke(action);
     }
 }
Beispiel #25
0
 /// <summary>
 /// Called when [shutdown].
 /// </summary>
 /// <param name="shutdownEvent">The shutdown event.</param>
 private void OnShutdown(ShutdownEvent shutdownEvent)
 {
     dispatcher.BeginInvoke(new Action(() =>
     {
         var wins = windows.Values.ToArray();
         foreach (var window in wins)
         {
             window.Close();
         }
     }));
 }
Beispiel #26
0
 public static void EasyBeginInvoke(this IDispatcher dispatcher, Delegate method, object arg)
 {
     if (dispatcher.CheckAccess())
     {
         method.Method.Invoke(method.Target, new [] { arg });
     }
     else
     {
         dispatcher.BeginInvoke(method, arg);
     }
 }
 private void OnSetTopic(HelpTopic helpTopic)
 {
     try
     {
         _dispatcher.BeginInvoke(() => this.SetValue(HelpProvider.HelpTopicProperty, helpTopic));
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         throw;
     }
 }
Beispiel #28
0
 private void UpdateJobProfileFromCurrentProperties(object obj)
 {
     _dispatcher.BeginInvoke(() =>
     {
         var settings = _settingsProvider.Settings?.Copy();
         Profiles     = settings?.ConversionProfiles;
         if (Profiles != null)
         {
             SelectedProfile = Profiles.First(profile => profile.Name == _selectedProfileProvider.SelectedProfile.Name);
         }
     });
 }
        public Task NavigateBack()
        {
            if (!viewModels.TryPop(out var oldViewModel))
            {
                throw new Exception();
            }
            if (!viewModels.TryPeek(out var newViewModel))
            {
                throw new Exception();
            }

            var task = NavigateIntenal(newViewModel);

            return(task.ContinueWith(t =>
            {
                if (oldViewModel is IDisposable disposable)
                {
                    dispatcher.BeginInvoke(() => disposable.Dispose());
                }
            }));
        }
Beispiel #30
0
        public static void BeginInvokeOrDo(this IDispatcher dispatcher, Action action)
        {
            Contract.Requires(action != null, "action");

            if (dispatcher != null && dispatcher.InvokeRequired)
            {
                dispatcher.BeginInvoke(action);
            }
            else
            {
                action();
            }
        }
Beispiel #31
0
        public IEnumerable <AccountOverview> GetAccountsOverview()
        {
            var accounts = new ObservableCollection <AccountOverview>();

            _proxy.Invoke <IEnumerable <AccountOverview> >("GetAccountsOverview").ContinueWith(t =>
            {
                foreach (var accountOverview in t.Result)
                {
                    _dispatcher.BeginInvoke(() => accounts.Add(accountOverview));
                }
            });
            return(accounts);
        }
        public AccountsOverview(IDispatcher dispatcher)
        {
            _dispatcher = dispatcher;
            _accountBalanceChangedCallbacks = new List<AccountBalanceChanged>();

            var hubConnection = new HubConnection("http://localhost:9044/");
            hubConnection.TraceLevel = TraceLevels.All;
            hubConnection.TraceWriter = new DebugTextWriter();

            _proxy = hubConnection.CreateHubProxy("OverviewHub");
            _proxy.On("accountBalanceChanged", (string accountNumber, decimal amount) =>
            {
                _dispatcher.BeginInvoke(() =>
                {
                    foreach (var callback in _accountBalanceChangedCallbacks)
                    {
                        callback(accountNumber, amount);
                    }
                });
            });

            hubConnection.Start(new LongPollingTransport()).Wait();
        }