保持两个线程之间的同步布尔值线程、两个、布尔值

2023-09-03 04:29:38 作者:注定输给时间

在一个线程(线程2)我已经改变的值,例如

In one thread (thread2) I have changed a value e.g.

CheckSuccess = false;

现在主线程?(线程1 - GUI /表)不皮卡的变化,怎么会是可能的propogate的所有线程身边的变化

Now the main thread (thread1 - GUI / Form) does not pickup the change, how would it be possible to "propogate" the changes around all threads?

我下的是IM pression的线程应该处理数据,而不是在单独的情况下工作(除非告知这样做)

I was under the impression that threads should manipulate the data, not work on seperate instances (unless told to do so)

推荐答案

这似乎是一个竞争条件。为了避免这种情况,你应该同步的访问共享变量。

It seems like a Race Condition. To avoid this you should synchronize an access to the shared variables.

如果CheckSuccess是场 - 尝试通过挥发性关键字将其标记。

如果 CheckSuccess 是一个属性(将被转换为一个方法调用),可以使用的锁定()语句: If CheckSuccess is a field - try out marking it by volatile keyword.

If CheckSuccess is a property (which will be translated to a method call) you can use lock() statement:

private static readonly object stateLock = new object();
lock (stateLock)
{
    // access a shared variable here
    CheckSuccess  = false;
}

线程的生命周期 创建的两种方式及使用 线程的同步

如果 CheckSuccess 是UI控件的属性,你想从工作线程改变它 - 你应该使用特殊的技术,从工人到推送UI线程,这取决于哪个框架您正在使用WPF中的WinForms。

If CheckSuccess is a property of UI control and you want changing it from a worker thread - you should use special techniques to push changes from a worker to the UI thread, it depends on which framework you are using WinForms of WPF.

的WinForms - 如何从C#中的另一个线程更新GUI 在WPF - 更新WPF在运行时 控制 WinForms - How to update GUI from another thread in C#? WPF - Update WPF controls at run time

PS: 此外,如果你有编写多线程读取一个值,线程数(基本上比写作阅读更多的时候),你可能会发现有用的 ReaderWriterLock

PS: Also if you have multiple threads reading a value and few threads writing (basically reads more often than writing) you may find useful ReaderWriterLock