C# 如何正确阻止方法,直到对象计数器获得>;0?
你可以认为这门课很奇怪,但它是有教育意义的,所以我不得不这样做C# 如何正确阻止方法,直到对象计数器获得>;0?,c#,multithreading,asynchronous,C#,Multithreading,Asynchronous,你可以认为这门课很奇怪,但它是有教育意义的,所以我不得不这样做 class petriPool { private int[] nodes = new int[3]; private int counter; private readonly object _lock = new object(); public petriPool (int n, int m) { this.nodes[0] = n; this.nodes[
class petriPool {
private int[] nodes = new int[3];
private int counter;
private readonly object _lock = new object();
public petriPool (int n, int m) {
this.nodes[0] = n;
this.nodes[1] = 0;
this.nodes[2] = 0;
this.counter = m;
}
public bool start() {
lock (_lock) {
if (this.nodes[0] != 0 && counter != 0) {
this.nodes[0]--;
this.nodes[1]++;
counter--;
return true;
} else
return false;
}}
public bool stop() {
lock (_lock) {
if (this.nodes[1] != 0) {
this.nodes[1]--;
this.nodes[2]++;
counter++;
return true;
} else
return false;
}}
}
我需要使start()
方法等待计数器
获取值>0
。我可以这样做:
public bool start() {
while (this.counter == 0) {
Thread.Sleep(10);
}
lock (_lock) {
if (this.nodes[0] != 0 && counter != 0) {
this.nodes[0]--;
this.nodes[1]++;
counter--;
return true;
} else
return false;
}}
但这不是更好的解决办法吗?我的意思是看起来我可以少睡一会儿
看,看它需要什么。我在启动线程之前调用
start
,在线程结束时调用stop
。所以计数器必须反映在同一时间运行的最大线程数。这样的信号发送是通过使用事件类完成的。在你的情况下,应该足够了
你可以用它来代替while循环,当计数器为零时你也可以用它 您可以考虑使用“ManualResetEvent”在两个线程之间进行协作 以下未经测试的代码可能会有所帮助
class petriPool
{
private int[] nodes = new int[3];
private int counter;
private ManualResetEvent mevent;
private readonly object _lock = new object();
public petriPool (int n, int m)
{
mevent= new ManualResetEvent(false);
this.nodes[0] = n;
this.nodes[1] = 0;
this.nodes[2] = 0;
this.counter = m;
}
public bool start()
{
lock (_lock)
{
if (this.nodes[0] != 0 && counter != 0)
{
this.nodes[0]--;
this.nodes[1]++;
counter--;
if(counter>0) mevent.Set();
return true;
} else
return false;
}
}
public bool stop()
{
mevent.WaitOne();
lock (_lock) {
if (this.nodes[1] != 0) {
this.nodes[1]--;
this.nodes[2]++;
counter++;
return true;
} else
return false;
}
//reset 'mevent' if you want.
}
}
您的代码很难识别为C代码。看一看这张照片。这看起来就像是一本C++的书,谢谢!当我解决所有紧急问题时,我会读这篇文章。你们也可以看看
BlockingCollection
,而不是你们想要的数组。@YuvalItzchakov,看起来这是最好的解决方案。我对这个问题做了一些解释。我用5N和2个计数器创建对象。所有线程一次启动,当所有线程结束时,程序停止运行。看起来有点不对劲。