.NET 创建新的调度程序
我正在尝试使用调度程序创建第二个线程,以便我可以让主调度程序(用于 UI)完全无压力,并且让 UI 不断响应。
现在,我可以为每个子线程(或 C# 中的 void)创建多个线程,但我是否有可能创建一个新线程并获取它的调度程序,然后调用它?这就是我所做的:
Private CheckLoopThread As New System.Threading.Thread(New System.Threading.ThreadStart(AddressOf CheckLoop))
CheckLoopThread.Priority = System.Threading.ThreadPriority.Lowest
CheckLoopThread.Start()
Dim Test As Windows.Threading.Dispatcher = Windows.Threading.Dispatcher.FromThread(CheckLoopThread)
但是,变量“Test”在执行“Nothing”之后。这怎么可能?是创建第二个调度程序的另一种方法吗?
欢迎以任何 .NET 形式提供答案。 Visual Basic 或 C#。我正在 .NET 4.0 框架上使用 VB.NET WPF。
提前致谢。
I am trying to create a second thread with dispatcher so that I can have the primary dispatcher (for the UI) completely stress-free, and have the UI constantly respondant.
Now, I could create multiple threads for each sub (or void in C#), but isn't it possible for me to create one new thread and grab it's dispatcher, and invoke to that? This is what I've done:
Private CheckLoopThread As New System.Threading.Thread(New System.Threading.ThreadStart(AddressOf CheckLoop))
CheckLoopThread.Priority = System.Threading.ThreadPriority.Lowest
CheckLoopThread.Start()
Dim Test As Windows.Threading.Dispatcher = Windows.Threading.Dispatcher.FromThread(CheckLoopThread)
However, the variable "Test" is after execution "Nothing". How is this possible? Is the another way to create a second dispatcher?
Answers are appreciated in any .NET form. Visual Basic or C#. I am working in VB.NET WPF on the .NET 4.0 framework.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么要锁?
我更喜欢:
Why locking?
I prefer:
Dispatcher.FromThread(... )
不会创建 Dispatcher,如果尚未为线程创建 Dispatcher,则返回 null。要为线程创建调度程序,您必须访问Dispatcher.CurrentDispatcher
至少在您的CheckLoopThread
上运行一次。正如 MSDN 上针对Dispatcher.CurrentDispatcher
所说:Dispatcher.FromThread(...)
will not create a Dispatcher and will return null if a Dispatcher has not already been created for the thread. To create a Dispatcher for a thread, you will have to accessDispatcher.CurrentDispatcher
at least once on yourCheckLoopThread
. As it says on MSDN forDispatcher.CurrentDispatcher
:我实际上正在创建很多这样的调度程序,我想正确的方法是以下几行:
所有锁定似乎都很复杂,但理论上
Start()
方法可以在之前返回>dispatcher
实际上已设置,因此调用它可能会导致没有锁的NullReferenceException
。I'm actually creating a lot of these dispatchers, I guess the proper way is something along the following lines:
It seems complicated with all the locking, but theoretically the
Start()
method can return beforedispatcher
is actually set, so a call to to it might result in aNullReferenceException
without the locks.