调用特定线程C#的委托 [英] Invoke a delegate on a specific thread C#
问题描述
有没有什么办法让一个委托到一个特定的线程中运行。
Is there any way to get a delegate to run on a specific thread?
说我有:
CustomDelegate del = someObject.someFunction;
Thread dedicatedThread = ThreadList[x];
我可以有一个一致的后台长时间运行的线程,并调用我自己的代表,每当我需要它。它每次都相同的线程。
Can I have a consistent background long running thread and invoke my own delegates on it whenever I need it. It has to be the same thread each time.
为什么我希望它的原因上一个专门的线程是时候,是我上故意要在其上运行的委托,并暂停后是
毫秒的线程,恢复线程,当我在其上运行的另一个代表。我认为这是不可能的。我将有一个代表队列并让该线程的主要功能读取并运行它。
The reason why I want it to be on a dedicated thread is time is that I inten to run the delegate on it and suspend the thread after y
milliseconds, and resume the thread when I run another delegate on it. I see this isn't possible. I will have a delegate queue and let the main function of the thread read and run from it.
要与一个具体的例子阐明,我有一个游戏系统与一群球员的线程。我想每个playerthread运行事件处理程序上的游戏事件。如果事件处理程序花费太多时间,我想能够暂停特定的球员,直到被暂停其线程的下一个事件。
To clarify with a concrete example, I have a game system with a bunch of player threads. I would like each playerthread to run event handlers for game events on it. If the event handlers take too much time I would like to be able to pause that particular player until the next event by suspending its thread.
从而对,我可以运行多个事件处理程序专用线程我可以成为窃听的情况下暂停特定球员的AI或时间过长。
Thus having a dedicated thread on which I can run multiple event handlers I can pause a particular player's AI in case it became bugged or is taking too long.
推荐答案
我认为最好的解决办法是使用任务
对象,并将它们排队到< A HREF =http://blogs.msdn.com/b/pfxteam/archive/2010/04/07/9990421.aspx相对=nofollow> StaThreadScheduler 运行的单个线程。
I think the best solution is to use Task
objects and queue them to an StaThreadScheduler running a single thread.
另外,你可以使用 ActionThread
中的 Nito.Async 以创建动作
代表一个内置的队列中的正常主题。
Alternatively, you could use the ActionThread
in Nito.Async to create a normal thread with a built-in queue of Action
delegates.
然而,无论这些都会直接访问其它的需求:能够暂停一个动作,并继续与另一个。要做到这一点,你需要撒同步点贯穿每一个动作,并有一种方法来保存其状态,重新排队它,并继续下一个动作。
However, neither of these will directly address another need: the ability to "pause" one action and continue with another one. To do this, you'd need to sprinkle "synchronization points" throughout every action and have a way to save its state, re-queue it, and continue with the next action.
所有这些复杂性非常接近接近一个线程调度系统,所以我建议退后一步,做多了重新设计。你可以让每一个动作来排队到线程池
(我建议只是有每个人是一个工作
)对象。您仍然需要撒同步点,但不是保存状态,重新排队它们,你只需要暂停(块)它们。
All that complexity is very nearly approaching a thread scheduling system, so I recommend taking a step back and doing more of a re-design. You could allow each action to be queued to the ThreadPool
(I recommend just having each one be a Task
object). You'll still need to sprinkle "synchronization points", but instead of saving state and re-queueing them, you'll just need to pause (block) them.
这篇关于调用特定线程C#的委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!