方法Stop无法在另一个线程中修改字段isRunning,为什么?
以下是来自MSDN的示例,但该字段仅由一个线程修改。
http://msdn.microsoft.com/en-us/library/x13ttww7(v=vs.110).aspx
以下是我的代码。
public class Worker { private volatile bool isRunning; public void Run() { ThreadPool.QueueUserWorkItem(DoSomething); } public void Stop() { this.isRunning = false; } private void DoSomething(object state) { this.isRunning = true; while (this.isRunning) { Console.WriteLine("working..."); Thread.Sleep(1000); } Console.WriteLine("stopped."); } }The method Stop can't modifies field isRunning in another thread, why?
Here is a sample from MSDN, but the field is modified by only one thread.
http://msdn.microsoft.com/en-us/library/x13ttww7(v=vs.110).aspx
Following is my code.
public class Worker { private volatile bool isRunning; public void Run() { ThreadPool.QueueUserWorkItem(DoSomething); } public void Stop() { this.isRunning = false; } private void DoSomething(object state) { this.isRunning = true; while (this.isRunning) { Console.WriteLine("working..."); Thread.Sleep(1000); } Console.WriteLine("stopped."); } }最满意答案
它确实有效。 如果您运行此代码,您将看到它工作正常:
Worker worker = new Worker(); worker.Run(); Thread.Sleep(1000); worker.Stop();问题是当您安排执行线程时,需要一些时间来执行。 在我的示例中跳过Thread.Sleep(1000)的情况下,立即将isRunning字段设置为false,然后在执行线程时将其设置为true。 这就是它永远不会完成的原因。
It actually works. If you run this code, you will see that it works just fine:
Worker worker = new Worker(); worker.Run(); Thread.Sleep(1000); worker.Stop();The problem is that when you schedule a thread for execution, it needs some time to execute. In a case when you skip the Thread.Sleep(1000) in my example, you immediately set the isRunning field to false, which is then set to true when the thread executes. That's why it never finishes.
更多推荐
发布评论