c# - AutoResetEvent 与 bool 值停止线程

标签 c# multithreading autoresetevent

我在工作线程中有一个对象,我可以指示它停止运行。我可以使用 bool 或 AutoResetEvent 来实现:

bool 值:

private volatile bool _isRunning;

public void Run() {
    while (_isRunning)
    {
        doWork();
        Thread.Sleep(1000);
    }
}

自动重置事件:

private AutoResetEvent _stop;

public void Run() {
    do {
        doWork();
    } while (!_stop.WaitOne(1000));
}

然后 Stop() 方法会将 _isRunning 设置为 false,或调用 _stop.Set()

除了 AutoResetEvent 的解决方案可能会停止得更快一点,这些方法之间有什么区别吗?一个比另一个“更好”吗?

最佳答案

C# volatile 不提供所有保证。它可能仍然读取过时的数据。最好使用底层操作系统同步机制,因为它提供了更强大的保证。

所有这一切都非常深入 discussed作者 Eric Lippert(非常值得一读),这里是简短的引用:

In C#, "volatile" means not only "make sure that the compiler and the jitter do not perform any code reordering or register caching optimizations on this variable". It also means "tell the processors to do whatever it is they need to do to ensure that I am reading the latest value, even if that means halting other processors and making them synchronize main memory with their caches".

Actually, that last bit is a lie. The true semantics of volatile reads and writes are considerably more complex than I've outlined here; in fact they do not actually guarantee that every processor stops what it is doing and updates caches to/from main memory. Rather, they provide weaker guarantees about how memory accesses before and after reads and writes may be observed to be ordered with respect to each other. Certain operations such as creating a new thread, entering a lock, or using one of the Interlocked family of methods introduce stronger guarantees about observation of ordering. If you want more details, read sections 3.10 and 10.5.3 of the C# 4.0 specification.

Frankly, I discourage you from ever making a volatile field. Volatile fields are a sign that you are doing something downright crazy: you're attempting to read and write the same value on two different threads without putting a lock in place. Locks guarantee that memory read or modified inside the lock is observed to be consistent, locks guarantee that only one thread accesses a given hunk of memory at a time, and so on.

关于c# - AutoResetEvent 与 bool 值停止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11953234/

相关文章:

c# - 在 ASP.NET MVC 中提交表单后显示值的最佳实践

c++ - pthread_create 参数传递错误

multithreading - 超过 400 个连接的 Indy TCP 服务器

c# - 是否有一个 WaitOne 方法本质上首先调用 Reset?

c# - 在 Visual Studio 2015 中连接到数据库

c# - C#winform-如何删除多个DataGridViewRows

c# - 如何在 asp.net 应用程序中从 jquery 设置 HttpPost 端点

java - 使用线程的 Hibernate session 和事务

c# - 单例 - 构造函数内的任务无法启动/不异步启动

c# - C# 中的队列和等待句柄