gpt4 book ai didi

c# - 在对象计数器 > 0 之前,我如何正确地阻止方法?

转载 作者:太空宇宙 更新时间:2023-11-03 10:33:48 25 4
gpt4 key购买 nike

你可以觉得上课很奇怪,但它很有教育意义,所以我必须这样做。

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() 方法等到 counter 获得值 > 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;
}}

但是这里没有更好的解决方案吗?我的意思是看起来我可以减少 sleep 时间。

为了看到它所需要的。我在启动线程之前调用 start,在线程结束时调用 stop。所以计数器必须反射(reflect)同时运行的最大线程数。

最佳答案

像这样的信号是通过使用事件类完成的。在你的情况下,ManualResetEventSlim应该足够了。

您可以 Wait对于它而不是 while 循环,你可以 Set当计数器归零时。

关于c# - 在对象计数器 > 0 之前,我如何正确地阻止方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28712350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com