Using VerifyAccess and CheckAccess Methods for DispatcherObject

Looking through this article , I came across this statement -

If you write your own WPF objects, such as controls, all the methods you need to call VerifyAccess before they do any work. This ensures that your objects are used in the user interface thread, e.g.

//Using VerifyAccess and CheckAccess 
public class MyWpfObject : DispatcherObject
{
    public void DoSomething()       
    {
        VerifyAccess();

        // Do some work
    }

    public void DoSomethingElse()
    {
        if (CheckAccess())
        {
            // Something, only if called 
            // on the right thread
        }
    }
}

I did not see this in any of the custom controls I came across (as far as I remember).

  • Do you use this when creating custom controls?
  • Should it be done or just nice to have?
  • Has anyone encountered a problem due to the lack of this in your controls?
+3
1

, . , - Custom Controls. WPF Toolkit.

, -, . , :

// Don't do this in all methods of your custom control!
public void Foo()
{
  if (!CheckAccess())
  {
    Dispatcher.Invoke(()=> Foo()); // Transit to UI Thread
    return;
  }
  // .. do work in UI.
}

. , , . ? - !

1. Dispatcher.Invoke(), , . . , Dispatcher.BeginInvoke(), , . - , , , .

2. Foo() , UI. , :

// Somewhere not in UI
for (int i = 0; i < 1000000; i++)
{
  control.Foo(); // Looks good, but performance is awful!
}

, 1000000 , , , , , .

, WPF , , UI. , , - :).

, .

+6

Source: https://habr.com/ru/post/1763413/


All Articles