Exemple #1
0
        public static void InvokeOnGui(this DispatcherObject application, DispatcherPriority priority, Action action)
        {
            Safeguard.EnsureNotNull("application", application);
            Safeguard.EnsureNotNull("action", action);

            Dispatcher dispatcher = application.Dispatcher;

            if (dispatcher == null || dispatcher.CheckAccess())
            {
                action();
            }
            else
            {
                dispatcher.Invoke(priority, action);
            }
        }
        /// <summary>
        /// Executes the specified <see cref="Action"/> asynchronously on the
        /// thread the <see cref="Dispatcher"/> is associated with.
        /// </summary>
        /// <param name="dispatcherObject">The dispatcher object, usually a UI control to use for thread-safe invocation</param>
        /// <param name="action">The delegate to invoke through the dispatcher.</param>
        public static void CheckAndBeginInvoke(this DispatcherObject dispatcherObject, Action action)
        {
            if (dispatcherObject != null)
            {
                var dispatcher = dispatcherObject.Dispatcher;

                if (dispatcher.CheckAccess())
                {
                    action();
                }
                else
                {
                    dispatcher.BeginInvoke(action);
                }
            }
        }
        protected virtual void DispatchOnPropertyChanged(DispatcherObject obj, object sender, DispatcherPriority priority = DispatcherPriority.Normal, [CallerMemberName] string name = null)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            var dispatcher = obj?.Dispatcher ?? Dispatcher.CurrentDispatcher;

            if (dispatcher == null || dispatcher.HasShutdownStarted || dispatcher.HasShutdownFinished)
            {
                return;
            }

            dispatcher.Invoke(() => OnPropertyChanged(sender, new PropertyChangedEventArgs(name)), priority);
        }
        public static void InvokeAsync(DispatcherObject dispatcherObject, Action action, DispatcherPriority priority = DispatcherPriority.Normal, AsyncInvokeMode mode = AsyncInvokeMode.AsyncOnly)
        {
            if (dispatcherObject == null || dispatcherObject.Dispatcher == null)
            {
                return;
            }

            if (mode == AsyncInvokeMode.AllowSyncInvoke && dispatcherObject.Dispatcher.CheckAccess())
            {
                action.Invoke();
            }
            else
            {
                dispatcherObject.Dispatcher.BeginInvoke(action, priority);
            }
        }
 /// <summary>
 /// ListBoxLogMessageAdd
 /// </summary>
 /// <param name="message"></param>
 /// <param name="color"></param>
 public void ListBoxLogMessageAdd(string message, System.Windows.Media.Brush color)
 {
     if (DispatcherObject.Thread != Thread.CurrentThread)
     {
         DispatcherObject.Invoke(new DMessageAdd(ListBoxLogMessageAdd), DispatcherPriority.ApplicationIdle, message, color);
     }
     else
     {
         MessageList.Add(new ListBoxLogMessageString(String.Format("{0} {1}", ++_counter, message), color, FontWeights.Normal, 14));
         listBox_LogMessages.SelectedIndex = listBox_LogMessages.Items.Count - 1;
         listBox_LogMessages.ScrollIntoView(listBox_LogMessages.SelectedItem);
         if (MessageList.Count > MAX_MESSGAES)
         {
             MessageList.RemoveAt(0);
         }
     }
 }
        public static void Invoke(Action action)
        {
            DispatcherObject dispatcher =
                Application.Current;

            if (dispatcher == null ||
                dispatcher.CheckAccess() ||
                dispatcher.Dispatcher == null
                )
            {
                action();
            }
            else
            {
                SafeInvoke(action);
            }
        }
Exemple #7
0
        public static void RunOnUIThread(this DispatcherObject d, Action action)
        {
            Dispatcher dispatcher = d?.Dispatcher;

            if (dispatcher == null)
            {
                return;
            }
            if (dispatcher.CheckAccess())
            {
                action();
            }
            else
            {
                dispatcher.BeginInvoke((Delegate)action, Array.Empty <object>());
            }
        }
Exemple #8
0
        /// <summary>
        /// 不会重复的行为,短时间内双击等操作都不会重复触发行为
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="action"></param>
        public static void NotRepeatedAction(this DispatcherObject obj, Guid actionId, Action <Action> action)
        {
            EventProtector <Action> protector = null;

            if (!_protectors.TryGetValue(actionId, out protector))
            {
                lock (_protectors)
                {
                    if (!_protectors.TryGetValue(actionId, out protector))
                    {
                        protector = new EventProtector <Action>();
                        _protectors.Add(actionId, protector);
                    }
                }
            }
            protector.Start(action, () => { protector.End(); });
        }
Exemple #9
0
        /// <summary>
        /// Returns a dispatcher for multi-threaded scenarios
        /// </summary>
        /// <returns></returns>
        internal static Dispatcher GetDispatcher(this DispatcherObject source)
        {
            //use the application's dispatcher by default
            if (Application.Current != null)
            {
                return(Application.Current.Dispatcher);
            }

            //fallback for WinForms environments
            if (source.Dispatcher != null)
            {
                return(source.Dispatcher);
            }

            //ultimatively use the thread's dispatcher
            return(Dispatcher.CurrentDispatcher);
        }
Exemple #10
0
 protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs args)
 {
     if (this.CollectionChanged != null)
     {
         foreach (NotifyCollectionChangedEventHandler handler in this.CollectionChanged.GetInvocationList())
         {
             DispatcherObject dispatcherObject = handler.Target as DispatcherObject;
             if (dispatcherObject != null)
             {
                 dispatcherObject.Dispatcher.Invoke(handler, handler, args);
             }
             else
             {
                 handler(handler, args);
             }
         }
     }
 }
        protected virtual void OnPropertyChanged(DispatcherObject obj, object sender, [CallerMemberName] string name = null)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            var dispatcher = obj?.Dispatcher ?? Dispatcher.CurrentDispatcher;

            if (dispatcher != null && !dispatcher.CheckAccess())
            {
                dispatcher.Invoke(() => OnPropertyChanged(sender, new PropertyChangedEventArgs(name)));
            }
            else
            {
                OnPropertyChanged(sender, new PropertyChangedEventArgs(name));
            }
        }
        public static T Invoke <T>([NotNull] this DispatcherObject dispatcherObject, [NotNull] Func <T> func)
        {
            if (dispatcherObject == null)
            {
                throw new ArgumentNullException(nameof(dispatcherObject));
            }
            if (func == null)
            {
                throw new ArgumentNullException(nameof(func));
            }

            if (dispatcherObject.Dispatcher.CheckAccess())
            {
                return(func());
            }

            return((T)dispatcherObject.Dispatcher.Invoke(func));
        }
Exemple #13
0
 /// <summary>
 /// WPF使用的带异常处理的BeginInvoke
 /// </summary>
 public static void TryBeginInvoke(this DispatcherObject ctrl, Action action, Action <Exception> errorAction = null)
 {
     ctrl.Dispatcher.BeginInvoke(new Action(() =>
     {
         try
         {
             action();
         }
         catch (Exception ex)
         {
             if (errorAction != null)
             {
                 errorAction(ex);
             }
             LogUtil.Error(ex);
         }
     }));
 }
Exemple #14
0
 public static void DispatcherInvoke <T>(this DispatcherObject dispatcherObj, Action <T> action, T param)
 {
     if (!dispatcherObj.Dispatcher.CheckAccess())
     {
         dispatcherObj.Dispatcher.Invoke(new DispatcherInvokeOneParamActionDelegate <T>(DispatcherInvoke), dispatcherObj, action, param);
     }
     else
     {
         try
         {
             action(param);
         }
         catch (Exception e)
         {
             Logger.Error("DispatcherInvoke - error while action execution", e);
         }
     }
 }
Exemple #15
0
 public static T Invoke <T>(this DispatcherObject dispatcher, Func <T> func)
 {
     try
     {
         if (dispatcher.CheckAccess())
         {
             return(func());
         }
         else
         {
             return(dispatcher.Dispatcher.Invoke(func));
         }
     }
     catch (TaskCanceledException ex)
     {
         Console.WriteLine(ex);
         Console.WriteLine("执行代码中,控件可能已释放...");
         return(default);
Exemple #16
0
        /// <summary>
        /// Checks if to CAO have the same context affinity. This is for example important for
        /// ContainerVisual.Children.Add to ensure that the scene graph is homogenously build out
        /// of object that have the same context affinity.
        /// </summary>
        /// <param name="reference">Reference to which to compare to. This argument is usually the this
        /// pointer and can not be null.</param>
        /// <param name="other">Object for which the check is performed.</param>
        /// <remarks>
        /// Example:
        ///
        /// class Visual
        /// {
        ///     ...
        ///     void Add(Visual child)
        ///     {
        ///         VerifyContext(this);
        ///         AssertSameContext(this, child);
        ///         ...
        ///     }
        /// }
        ///
        /// Note that VerifyContext(A) AND AssertSameContext(A, B) implies that VerifyContext(B) holds. Hence you
        /// don't need to check the context for each argument if you assert the same context.
        /// </remarks>
        internal static void AssertSameContext(
            DispatcherObject reference,
            DispatcherObject other)
        {
            Debug.Assert(reference != null, "The reference object can not be null.");

            // DispatcherObjects may be created with the option of becoming unbound.
            // An unbound DO may be created without a Dispatcher or may detach from
            // its Dispatcher (e.g., a Freezable).  Unbound DOs return null for their
            // Dispatcher and should be accepted anywhere.
            if (other != null &&
                reference.Dispatcher != null &&
                other.Dispatcher != null &&
                reference.Dispatcher != other.Dispatcher)
            {
                throw new ArgumentException(SR.Get(SRID.MediaSystem_ApiInvalidContext));
            }
        }
Exemple #17
0
        /// <summary>
        /// Overriden for speed improvements, see: http://shevaspace.spaces.live.com/Blog/cns!FD9A0F1F8DD06954!547.entry
        /// </summary>
        /// <param name="e"></param>
        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            if (this.CollectionChanged != null)
            {
                using (IDisposable disposable = this.BlockReentrancy())
                {
                    foreach (Delegate del in this.CollectionChanged.GetInvocationList())
                    {
                        NotifyCollectionChangedEventHandler handler = (NotifyCollectionChangedEventHandler)del;
                        DispatcherObject   dispatcherInvoker        = del.Target as DispatcherObject;
                        ISynchronizeInvoke syncInvoker = del.Target as ISynchronizeInvoke;
                        if (dispatcherInvoker != null)
                        {
                            // We are running inside DispatcherSynchronizationContext,
                            // so we should invoke the event handler in the correct dispatcher.
                            dispatcherInvoker.Dispatcher.Invoke(DispatcherPriority.Normal, new ThreadStart(delegate
                            {
                                try
                                {
                                    handler(this, e);
                                }
                                catch (Exception)
                                {
                                    // MWA: Swallow the exception here because it usually is the result of something else
                                }
                            }));
                        }
                        else if (syncInvoker != null)
                        {
                            // We are running inside WindowsFormsSynchronizationContext,
                            // so we should invoke the event handler in the correct context.
                            syncInvoker.Invoke(del, new Object[] { this, e });
                        }
                        else
                        {
                            // We are running in free threaded context, so just directly invoke the event handler.
                            handler(this, e);
                        }
                    }
                }
            }

            OnPropertyChanged(new PropertyChangedEventArgs("Count"));
        }
        public static void  DoEvents(this DispatcherObject obj, DispatcherPriority dispatcherPriority)
        {
            if (!obj.Dispatcher.CheckAccess())
            {
#if DEBUG
                Debugger.Break();
#endif
                //new ThreadStart();
                obj.Dispatcher.Invoke(DispatcherPriority.Normal, (Action <UIElement, DispatcherPriority>)DoEvents, obj, dispatcherPriority);
                return;
            }

            obj.Dispatcher.Invoke(dispatcherPriority, EmptyDelegate);

            //var frame = new DispatcherFrame();
            //obj.Dispatcher.BeginInvoke(dispatcherPriority,
            //                            new ExitFrameHandler(frm => frm.Continue = false), frame);
            //Dispatcher.PushFrame(frame); // blocks until Continue == false, which happens only when all operations with priority greater than Background have been processed by the Dispatcher.
        }
Exemple #19
0
 public static T InvokeIfNecessary <T>(this DispatcherObject dispatcherObject, Func <T> func)
 {
     if (dispatcherObject == null)
     {
         throw new ArgumentNullException(nameof(dispatcherObject));
     }
     if (func == null)
     {
         throw new ArgumentNullException(nameof(func));
     }
     if (dispatcherObject.Dispatcher.CheckAccess())
     {
         return(func());
     }
     else
     {
         return((T)dispatcherObject.Dispatcher.Invoke(func));
     }
 }
Exemple #20
0
        public static void RunInBackground(Action backgroundAction, DispatcherObject control, Action uiAction)
        {
            BackgroundWorker bgWorker = new BackgroundWorker
            {
                WorkerReportsProgress      = true,
                WorkerSupportsCancellation = false
            };

            var arg = new RunInBackgroundArgument()
            {
                Control          = control,
                BackgroundAction = backgroundAction,
                UIAction         = uiAction
            };

            bgWorker.DoWork             += RunInBackground_DoWork;
            bgWorker.RunWorkerCompleted += RunInBackground_RunWorkerComplete;
            bgWorker.RunWorkerAsync(arg);
        }
Exemple #21
0
        internal void RemoveOwner(DispatcherObject owner)
        {
            UIElement frameworkElement = owner as UIElement;

            if (frameworkElement != null && this.ownerFEs != null)
            {
                this.ownerFEs.Remove(frameworkElement);
                if (this.ownerFEs.Count == 0)
                {
                    this.ownerFEs = null;
                }
            }
            if (owner == this.inheritanceContext)
            {
                this.RemoveInheritanceContextFromValues();
                this.inheritanceContext = null;
            }
            this.RemoveOwnerFromAllMergedDictionaries(owner);
        }
Exemple #22
0
 public static void Invoke([NotNull] this DispatcherObject dispatcherObject, [NotNull] Action invokeAction)
 {
     if (dispatcherObject == null)
     {
         throw new ArgumentNullException(nameof(dispatcherObject));
     }
     if (invokeAction == null)
     {
         throw new ArgumentNullException(nameof(invokeAction));
     }
     if (dispatcherObject.Dispatcher.CheckAccess())
     {
         invokeAction();
     }
     else
     {
         dispatcherObject.Dispatcher.Invoke(invokeAction);
     }
 }
Exemple #23
0
        /// <summary>
        /// This collection changed event performs thread safe event raising.
        /// </summary>
        /// <param name="e">The event argument.</param>
        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            // Recommended is to avoid reentry
            // in collection changed event while collection
            // is getting changed on other thread.
            using (BlockReentrancy())
            {
                if (!this.suspendCollectionChangeNotification)
                {
                    NotifyCollectionChangedEventHandler eventHandler =
                        this.CollectionChanged;
                    if (eventHandler == null)
                    {
                        return;
                    }

                    // Walk thru invocation list.
                    Delegate[] delegates = eventHandler.GetInvocationList();

                    foreach
                    (NotifyCollectionChangedEventHandler handler in delegates)
                    {
                        // If the subscriber is a DispatcherObject and different thread.
                        DispatcherObject dispatcherObject
                            = handler.Target as DispatcherObject;

                        if (dispatcherObject != null &&
                            !dispatcherObject.CheckAccess())
                        {
                            // Invoke handler in the target dispatcher's thread...
                            // asynchronously for better responsiveness.
                            dispatcherObject.Dispatcher.BeginInvoke
                                (DispatcherPriority.DataBind, handler, this, e);
                        }
                        else
                        {
                            // Execute handler as is.
                            handler(this, e);
                        }
                    }
                }
            }
        }
Exemple #24
0
        string WpfToXaml(DispatcherObject dispObj)
        {
            if (dispObj != null)
            {
                // Get the XAML for the template.
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent              = true;
                settings.IndentChars         = new String(' ', 4);
                settings.NewLineOnAttributes = true;
                StringBuilder sb     = new StringBuilder();
                XmlWriter     writer = XmlWriter.Create(sb, settings);
                XamlWriter.Save(dispObj, writer);

                return(sb.ToString());
            }
            else
            {
                return("NULL");
            }
        }
Exemple #25
0
 protected void OnFrameReady(IFrame frame)
 {
     if (FrameReady != null)
     {
         DeviceFrameReadyHandler eventHandler = FrameReady;
         Delegate[] delegates = eventHandler.GetInvocationList();
         foreach (DeviceFrameReadyHandler handler in delegates)
         {
             DispatcherObject dispatcherObject = handler.Target as DispatcherObject;
             if (dispatcherObject != null && !dispatcherObject.CheckAccess())
             {
                 dispatcherObject.Dispatcher.Invoke(DispatcherPriority.DataBind, handler, this, frame);
             }
             else
             {
                 handler(this, frame);
             }
         }
     }
 }
Exemple #26
0
        public override void OnInvoke(MethodInterceptionArgs args)
        {
            DispatcherObject dispatcherObject = (DispatcherObject)args.Instance;

            if (this.Async)
            {
                // Invoke the method asynchronously on the GUI thread.
                dispatcherObject.Dispatcher.BeginInvoke(this.priority, new Action(args.Proceed));
            }
            else if (dispatcherObject.CheckAccess())
            {
                // We have access to the GUI object. Invoke the method synchronously.
                args.Proceed();
            }
            else
            {
                // We don't have access to the GUI thread. Invoke the method synchronously on that thread.
                dispatcherObject.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(args.Proceed));
            }
        }
Exemple #27
0
 private void OnBitmapFrameCaptured(BitmapFrame frame)
 {
     if (BitmapFrameCaptured != null)
     {
         BitmapFrameCapturedHandler eventHandler = BitmapFrameCaptured;
         Delegate[] delegates = eventHandler.GetInvocationList();
         foreach (BitmapFrameCapturedHandler handler in delegates)
         {
             DispatcherObject dispatcherObject = handler.Target as DispatcherObject;
             if (dispatcherObject != null && !dispatcherObject.CheckAccess())
             {
                 dispatcherObject.Dispatcher.Invoke(DispatcherPriority.DataBind, handler, frame);
             }
             else
             {
                 handler(frame);
             }
         }
     }
 }
Exemple #28
0
 protected void OnButtonStateChanged(Button button, bool pressed)
 {
     if (ButtonStateChanged != null)
     {
         ButtonStateChangedHandler eventHandler = ButtonStateChanged;
         Delegate[] delegates = eventHandler.GetInvocationList();
         foreach (ButtonStateChangedHandler handler in delegates)
         {
             DispatcherObject dispatcherObject = handler.Target as DispatcherObject;
             if (dispatcherObject != null && !dispatcherObject.CheckAccess())
             {
                 dispatcherObject.Dispatcher.Invoke(DispatcherPriority.DataBind, handler, button, pressed);
             }
             else
             {
                 handler(button, pressed);
             }
         }
     }
 }
Exemple #29
0
        public static void Invoke(DispatcherObject obj, Action action)
        {
            Debug.Assert(!obj.Dispatcher.CheckAccess( ));

            try
            {
                obj.Dispatcher.Invoke(
                    () => Execute(action),
                    DispatcherPriority.Background);
            }
            catch (Exception exc)
            {
                _ = exc;
                if (Debugger.IsAttached && !(exc is TaskCanceledException))
                {
                    Debugger.Break( );
                }
                throw;
            }
        }
Exemple #30
0
 protected void OnControllerAxisChanged(ControllerJoystick joystick, ControllerJoystickAxis axis, byte oldValue, byte newValue)
 {
     if (AxisChanged != null)
     {
         ControllerAxisChangedHandler eventHandler = AxisChanged;
         Delegate[] delegates = eventHandler.GetInvocationList();
         foreach (ControllerAxisChangedHandler handler in delegates)
         {
             DispatcherObject dispatcherObject = handler.Target as DispatcherObject;
             if (dispatcherObject != null && !dispatcherObject.CheckAccess())
             {
                 dispatcherObject.Dispatcher.Invoke(DispatcherPriority.DataBind, handler, joystick, axis, oldValue, newValue);
             }
             else
             {
                 handler(joystick, axis, oldValue, newValue);
             }
         }
     }
 }