DispatcherObject 继承和用法...我没有得到什么?
所以这是我的代码:
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);
}
}
现在...我期望的输出是创建的线程检查调度程序访问,查看它位于不同的线程上,然后在原始线程上调用 AccessDC(...)然后检查并查看它是否位于正确的线程上并调用 dc.Print(...)。
实际发生的情况是,它到达 CheckAccess() 并正确地发现它不在正确的线程上,然后调用 Invoke(...) 并在那里停止。
任何有关调度员如何工作的见解将不胜感激。
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
调度程序需要消息泵,控制台应用程序默认没有消息泵。尝试将其作为 GUI 应用程序运行 - 这将有一个消息泵。
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 验证了您的 CurrentThread DispatchClass 是当前线程,因此它返回给您 False。这是很正常的。
在这段代码中,
您遇到了参数问题,仅此而已。
这段代码有效:
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
You have a problem with arguments that's all.
this snippet of code works :