CheckAccess() приватный Метод

private CheckAccess ( ) : bool
Результат bool
Пример #1
0
        /// <summary>
        /// Checks whether the current thread is the thread that the dispatcher is associated with.
        /// </summary>
        /// <returns>True if it is on the thread that the Dispatcher is associated with; otherwise false.</returns>
        private bool IsInDispatcherThread()
        {
#if NICENIS_UWP
            return(TheWindow.Current.Dispatcher.HasThreadAccess);
#else
            return(_dispatcher.CheckAccess());
#endif
        }
Пример #2
0
        /// <summary>
        /// Raises the <see cref="TaskComplete"/> event.</summary>
        /// <param name="sender">
        /// The <see cref="Object"/> sending the event.</param>
        /// <remarks><para>
        /// <b>OnTaskComplete</b> raises the <see cref="TaskComplete"/> event. Use this method to
        /// notify any listeners that work on the current task is complete.
        /// </para><para>
        /// If <see cref="Dispatcher"/> is valid and <see cref="SysDispatcher.CheckAccess"/> fails,
        /// <b>OnTaskComplete</b> performs an asynchronous delegate invocation via <see
        /// cref="SysDispatcher.BeginInvoke"/> and with the current <see cref="Priority"/>.
        /// </para></remarks>

        public void OnTaskComplete(object sender)
        {
            var handler = TaskComplete;

            if (handler != null)
            {
                if (Dispatcher != null && !Dispatcher.CheckAccess())
                {
                    foreach (EventHandler eh in handler.GetInvocationList())
                    {
                        Dispatcher.BeginInvoke(Priority, eh, sender, EventArgs.Empty);
                    }
                }
                else
                {
                    handler(sender, EventArgs.Empty);
                }
            }
        }
Пример #3
0
 /// <summary>
 /// Invoke the provided delegate on the underlying actor and wait for completion.
 /// </summary>
 /// <param name="action">The action to invoke</param>
 public static void Invoke(Action action)
 {
     if (s_mainThreadDispather == null || s_mainThreadDispather.CheckAccess())
     {
         action.Invoke();
     }
     else
     {
         s_mainThreadDispather.Invoke(action);
     }
 }
Пример #4
0
 /// <summary>
 /// Invoke or execute
 /// </summary>
 /// <param name="dispatcher">The dispatcher</param>
 /// <param name="action">Action object</param>
 public static void InvokeOrExecute(this System.Windows.Threading.Dispatcher dispatcher, Action action)
 {
     if (dispatcher.CheckAccess())
     {
         action();
     }
     else
     {
         dispatcher.BeginInvoke(DispatcherPriority.Normal, action);
     }
 }
Пример #5
0
 public static void AppShutdownDispatcher(Dispatcher theMainDispatcher)
 {
     if (theMainDispatcher.CheckAccess())
     {
         theMainDispatcher.InvokeShutdown();
     }
     else
     {
         Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Send, (Action)(() =>
         {
             theMainDispatcher.InvokeShutdown();
         }));
     }
 }
Пример #6
0
 public static void ScrollToEnd(Dispatcher dispatcher, ListBox listBox)
 {
     if (dispatcher.CheckAccess())
     {
         SelectLastEntry(listBox);
     }
     else
     {
         dispatcher.BeginInvoke(
             DispatcherPriority.Send,
             new VoidFunctionHandler(SelectLastEntry),
             listBox);
     }
 }
Пример #7
0
        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));
                };
        }
Пример #8
0
        public static void RunInDispatcher(Dispatcher dispatcher, DispatcherPriority priority, Action action)
        {
            if (action == null) { return; }

            if (dispatcher.CheckAccess())
            {
                // we are already on thread associated with the dispatcher -> just call action
                try
                {
                    action();
                }
                catch (Exception ex)
                {
                    //Log error here!
                }
            }
            else
            {
                // we are on different thread, invoke action on dispatcher's thread
                dispatcher.BeginInvoke(
                    priority,
                    (Action)(
                    () =>
                    {
                        try
                        {
                            action();
                        }
                        catch (Exception ex)
                        {
                        //Log error here!
                    }
                    })
                );
            }
        }
Пример #9
0
            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;
            }
Пример #10
0
        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--;
            }
        }
 public static void ExecuteOnUIThread(Action action, Dispatcher dispatcher)
 {
     if (dispatcher.CheckAccess())
         action();
     else
         dispatcher.BeginInvoke(action);
 }
        static void InvokeOnThread(Dispatcher dispatcher, Action action, DispatcherPriority priority = DispatcherPriority.Normal, bool forceAsyncInvoke = true) {
            if(dispatcher == null)
                return;

            if(!forceAsyncInvoke && dispatcher.CheckAccess())
                action();
            else
                dispatcher.BeginInvoke(action, priority);
        }
Пример #13
0
        public WPFBlitPresenter(DirectCanvasFactory directCanvas, int width, int height, Dispatcher dispatcher)
            : base(directCanvas)
        {
            m_width = width;
            m_height = height;

            /* Check and see if we are on the UI thread as we may want to support
             * multi-threaded scenarios */
            if (!dispatcher.CheckAccess())
            {
                dispatcher.Invoke((Action)delegate
                {
                    m_d3dImage = new D3DImage();
                });
            }
            else
            {
                m_d3dImage = new D3DImage();
            }

            /* Initialize our special layers */
            CreateLayer(m_width, m_height);
        }
Пример #14
0
        private static void ParseIcons(
            XmlReader reader, Dispatcher dispatcher,
            IDictionary<string, ImageSource> icons)
        {
            while (reader.ReadToFollowing("UUID"))
            {
                var id = reader.ReadElementContentAsString();

                if (reader.Name != "Data" &&
                    !reader.ReadToNextSibling("Data"))
                {
                    continue;
                }

                var data = Convert.FromBase64String(
                    reader.ReadElementContentAsString());

                BitmapImage image = null;

                if (dispatcher.CheckAccess())
                {
                    image = new BitmapImage();
                    image.SetSource(new MemoryStream(data));
                }
                else
                {
                    var wait = new ManualResetEvent(false);

                    dispatcher.BeginInvoke(() =>
                    {
                        image = new BitmapImage();
                        image.SetSource(new MemoryStream(data));

                        wait.Set();
                    });

                    wait.WaitOne();
                }
                if (!icons.ContainsKey(id))
                    icons.Add(id, image);
            }
        }
Пример #15
0
        /// <summary>
        /// The fire scanner state changed.
        /// </summary>
        /// <param name="dispatcher">
        /// The dispatcher.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private static void FireScannerStateChanged(Dispatcher dispatcher, NotifyScannerStateChangedEventArgs e)
        {
            NotifyScannerStateChangedEventHandler scannerStateChanged;
            lock (SyncRoot)
            {
                if (currentScan != e.Id)
                {
                    return;
                }

                scannerStateChanged = ScannerStateChanged;
            }

            if (scannerStateChanged != null)
            {
                if (dispatcher.CheckAccess())
                {
                    scannerStateChanged(null, e);
                }
                else
                {
                    dispatcher.Invoke(new Action<Dispatcher, NotifyScannerStateChangedEventArgs>(FireScannerStateChanged), DispatcherPriority.Send, dispatcher, e);
                }
            }
        }
Пример #16
0
 private void DispatchWhenRequired( Dispatcher d, Action a )
 {
     if( d.CheckAccess() ) a();
     else d.Invoke( a );
 }
Пример #17
0
        public void Generate3DModel(Dispatcher dispatcher)
        {
            if (!dispatcher.CheckAccess())
              {
            dispatcher.Invoke(() => Generate3DModel(dispatcher));
            return ;
              }

              if (m_lights.Count == 0)
              {
            m_lights.Add(new DirectionalLight(Color.FromRgb(0xFF, 0xFF, 0xFF), new Vector3D(4, 6, -5)));
            m_lights.Add(new DirectionalLight(Color.FromRgb(0xFF, 0xFF, 0xFF), new Vector3D(-4, -6, 5)));
            m_lights.Add(new AmbientLight(Color.FromRgb(0x6F, 0x5F, 0x5F)));
              }

              m_model3DGroup = new Model3DGroup();
              foreach (Light light in m_lights)
            m_model3DGroup.Children.Add(light);
              foreach (QbModelPart qbModelPart in m_parts)
              {
            qbModelPart.GenerateGeometry();
            foreach (GeometryModel3D geometryModel3D in qbModelPart.Geometry)
            {
              m_model3DGroup.Children.Add(geometryModel3D);
            }
              }

              //double maxX = m_parts.Max(n => n.Max.X);
              //double maxY = m_parts.Max(n => n.Max.Y);
              //double maxZ = m_parts.Max(n => n.Max.Z);
              //double minX = m_parts.Min(n => n.Min.X);
              //double minY = m_parts.Min(n => n.Min.Y);
              //double minZ = m_parts.Min(n => n.Min.Z);
              //BoundaryBox boundaryBox = new BoundaryBox(new Point3D(minX-0.5, minY-0.5, minZ-0.5), new Point3D(maxX + 0.5, maxY + 0.5, maxZ + 0.5), Colors.Purple);
              //m_model3DGroup.Children.Add(boundaryBox.GeometryModel3D);

              //double width = m_parts.Max(n => n.Width);
              //double height = m_parts.Max(n => n.Height);
              //double depth = m_parts.Max(n => n.Depth);
              //boundaryBox = new BoundaryBox(new Point3D(-0.5, -0.5, -0.5), new Point3D(width - 0.5, depth - 0.5, height - 0.5), Colors.Goldenrod);
              //m_model3DGroup.Children.Add(boundaryBox.GeometryModel3D);

              double maxX = m_parts.Max(n => n.Max.X) + 1;
              double maxY = m_parts.Max(n => n.Max.Y) + 1;
              double minX = m_parts.Min(n => n.Min.X);
              double minY = m_parts.Min(n => n.Min.Y);
              m_ground = new Ground((int) minX, (int) maxX, (int) minY, (int) maxY, Scale);
              foreach (GeometryModel3D geometryModel3D in m_ground.GeometryModel3D)
              {
            m_model3DGroup.Children.Add(geometryModel3D);
              }
        }
        /// <summary>
        /// Fires off your delegate asyncronously, using the threadpool or a full managed thread if needed.
        /// </summary>
        /// <param name="d">A void delegate - can be cast to (Action) from an anonymous delgate.</param>
        /// <param name="dr">A delegate with a return value of some sort - can be cast to (Func&lt;object&gt;) from an anonymous delgate with a return.</param>
        /// <param name="state">A user object that can be tracked through the returned result</param>
        /// <param name="getRetVal">If true, and the method/delgete returns something, it is included in the AsyncRes returned (after the method completes)</param>
        /// <param name="tryThreadPool">True to use the TP, otherwise just go to a ful lthread - good for long running tasks.</param>
        /// <param name="rMode">If true, will make sure no other instances are running your method.</param>
        /// <returns>AsyncRes with all kind of goodies for waiting, result values, etc.</returns>
        private static AsyncRes Do(Func<object> dr, Action d, bool getRetVal, object state, bool tryThreadPool, ReenteranceMode rMode, bool isAsync, Dispatcher dispatcher)
        {
            //get a generic MethodInfo for checks..
            MethodInfo mi = ((dr != null) ? dr.Method : d.Method);
            //make a unique key for output usage
            string key = string.Format("{0}{1}{2}{3}", ((getRetVal) ? "<-" : ""), mi.DeclaringType, ((mi.IsStatic) ? ":" : "."), mi.Name);
            //our custom return value, holds our delegate, state, key, etc.
            AsyncRes res = new AsyncRes(state, ((dr != null) ? (Delegate)dr : (Delegate)d), key, rMode);

            //Create a delegate wrapper for what we will actually invoke..
            Action Action = (Action)delegate
            {
                if (!BeforeInvoke(res)) return; //checks for reentrance issues and sets us up
                try
                {
                    if (res.IsCompleted) return;
                    if (dr != null)
                    {
                        res.retVal = dr();//use this one if theres a return
                    }
                    else
                    {
                        d();//otherwise the simpler Action
                    }
                }
                catch (Exception ex)
                { //we never want a rogue exception on a random thread, it can't bubble up anywhere
                    System.Diagnostics.Debug.WriteLine("Async Exception:" + ex);
                }
                finally
                {
                    FinishInvoke(res);//this will fire our callback if they used it, and clean up
                }
            };

            if (dispatcher != null)
            {
                res.control = dispatcher;
                res.result = AsyncAction.ControlInvoked;
                if (!isAsync)
                {
                    if (dispatcher.CheckAccess())
                    {
                        res.completedSynchronously = true;
                        Action();
                    }
                    else
                    {
                        dispatcher.BeginInvoke(Action);
                    }
                }
                else
                {
                    dispatcher.BeginInvoke(Action);
                }
                return res;
            } //don't catch these errors - if this fails, we shouldn't try a real thread or threadpool!

            if (tryThreadPool)
            {
                //we are going to use the .NET threadpool
                try
                {
                    //this is what actually fires this task off..
                    bool result = ThreadPool.QueueUserWorkItem(delegate { Action(); });
                    if (result)
                    {
                        res.result = AsyncAction.ThreadPool;
                        //this means success in queueing and running the item
                        return res;
                    }
                    else
                    {
                        //according to docs, this "won't ever happen" - exception instead, but just for kicks.
                        System.Diagnostics.Debug.WriteLine("Failed to queue in threadpool. Method: " + key);
                    }

                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Failed to queue in threadpool: " + ex.Message, "Method: " + key);
                }
            }

            //if we got this far, then something up there failed, or they wanted a dedicated thread
            Thread t = new Thread((ThreadStart)delegate { Action(); }) { IsBackground = true, Name = ("Async_" + key) };
            res.result = AsyncAction.Thread;
            t.Start();

            return res;
        }