DispatcherObject inheritance and usage…what am I not getting?

℡╲_俬逩灬. 提交于 2019-12-24 19:06:52

问题


So here is my code:

class Program
{
  static DispatchClass dc;

  [STAThread]
  static void Main(string[] args)
  {
    dc = new DispatchClass();

    Thread th = new Thread(AccessDC);
    th.Start();

    Console.ReadKey();
  }

  private delegate void AccessDCDelegate(object state);
  static private void AccessDC(object state)
  {
    if(dc.Dispatcher.CheckAccess())
      dc.Print("hello");
    else
      dc.Dispatcher.Invoke(new AccessDCDelegate(AccessDC));
  }
}

public class DispatchClass : DispatcherObject
{
  public void Print(string str)
  {  
    Console.WriteLine(str);
  }
}

Now...the output I would expect from this is for the created thread to check the dispatcher access, see that it is on a different thread and then invoke AccessDC(...) on the original thread which then checks and sees that it is on the correct thread and calls dc.Print(...).

What actually happens is it gets to CheckAccess() and correctly sees that it isn't on the correct thread, then calls Invoke(...) and stops there.

Any insight into how Dispatchers work would be greatly appreciated.

Thanks.


回答1:


The dispatcher requires a message pump, console apps do not have a message pump by default. Try running this as a GUI application instead - that will have a message pump.




回答2:


CheckAccess verified that your CurrentThread DispatchClass is the current thread so it returned to you False. which is quite normal. In this snippet of code

dc.Dispatcher.Invoke(new AccessDCDelegate(AccessDC));

You have a problem with arguments that's all.

this snippet of code works :

 public partial class MainWindow : Window
{
    static DispatchClass dc;

    public MainWindow()
    {
        InitializeComponent();


        dc = new DispatchClass();

        Thread th = new Thread(AccessDC);
        th.Start();

    }
    private delegate void AccessDCDelegate(object state);
    static private void AccessDC(object state)
    {
        if (dc.Dispatcher.CheckAccess())
            dc.Print("hello");
        else
            dc.Dispatcher.BeginInvoke(new Action(()=> AccessDC(null)));
    }

}

public class DispatchClass : DispatcherObject
{
    public void Print(string str)
    {
        MessageBox.Show(str);
    }
}


来源:https://stackoverflow.com/questions/6864033/dispatcherobject-inheritance-and-usage-what-am-i-not-getting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!