在C#中的多线程修改和访问中保持最新的字段?(Keep field up

编程入门 行业动态 更新时间:2024-10-22 08:40:28
在C#中的多线程修改和访问中保持最新的字段?(Keep field up-to-date in multiple thread modify&access in C#?)

方法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.

更多推荐

本文发布于:2023-08-06 05:21:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1444556.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   多线程   最新   field

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!