C#-如何唤醒睡眠线程?
|
通过进一步阅读,我自己解决了这个问题,我假设您应该引用线程而不是对象。现在可以使用了。 :)
原始帖子:
我已经研究了大多数类似的问题,并且看到了许多包含监视器,脉冲等的答案,但是我无法使其正常工作。
我是C#的新手,所以如果我使用的线程错误,请原谅我。但是我的问题如下:
我有4个线程,其中一个将三个不同表的列中的整数减一。然后3个不同的线程根据某个值是否达到零来执行操作。
我想做的是让线程递减计数,如果某个值达到零,则仅唤醒其他三个线程的正确线程。要检查这不是问题,问题在于唤醒线程。我目前确实有一个可以同时运行的工具,但是我想使用它来提高效率。
这是我使用的代码,为简单起见,我仅包含其中一个,并且是相同的想法。这是我应该怎么用吗?
这是我在Google上阅读示例和结果后得到的。
public class UpdateQueueSuggestion
{
public void startGame()
{
Thread Check = new Thread(new ThreadStart(checkUpdate));
Check.Start();
}
public void checkUpdate()
{
// (...) Some intialization of variables
// Create the thread used for when entries in the Queue table reaches 0.
Thread Build = new Thread(new ThreadStart(performBuildingUpdate));
Build.Start();
// Some sqlcommands.
while (true)
{
try
{
// Enter to synchronize, if not it yields
// Object synchronization method was called from an unsynchronized block of code.
Monitor.Enter(this);
connection.Open();
// Execute commands. Get COUNT(*) for results reaching 0 in tables and save int in i.
if (i > 0)
{
// Pulse the thread called Build, in order to wake it again.
Monitor.Pulse(Build);
}
}
finally
{
// Exit monitor.
Monitor.Exit(this);
connection.Close();
}
// This one is supposed to run each second, decrement and check for zeros.
// Works just fine if I just put everything in here without monitors,
// but as I said I want to split it up for efficiency.
Thread.Sleep(1000);
}
}
public void performBuildingUpdate()
{
// Some sqlcommands
while (true)
{
Monitor.Enter(this);
try
{
connection.Open();
// Execute commands.
}
finally
{
connection.Close();
Monitor.Wait(this);
Monitor.Exit(this);
}
}
}
}
非常感谢任何帮助,谢谢。
如果有人想知道,那是为我们在学校为C#课程制作的浏览器游戏项目而设计的。这应该花费游戏事件的大概时间。目前,我们在一个线程中运行所有命令,并且每10秒运行一次。使它能够每秒运行将是很棒的。
没有找到相关结果
已邀请:
1 个回复
糖固傻染
每个工人正在运行类似: