开发者

DispatcherObject inheritance and usage...what am I not getting?

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.


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.


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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜