autoresetevent

C# Threading issue with AutoResetEvent

拈花ヽ惹草 提交于 2019-11-30 21:07:57
How to properly synchronize this? At the moment it is possible that SetData is called after e.WaitOne() has completed so d could be already set to another value. I tried to insert locks but it resulted into a deadlock. AutoResetEvent e = new AutoResetEvent(false); public SetData(MyData d) { this.d=d; e.Set(); // notify that new data is available } // This runs in separate thread and waits for d to be set to a new value void Runner() { while (true) { e.WaitOne(); // waits for new data to process DoLongOperationWith_d(d); } } Will the best solution be to introduce a new boolean variable

C# Threading issue with AutoResetEvent

前提是你 提交于 2019-11-30 05:11:03
问题 How to properly synchronize this? At the moment it is possible that SetData is called after e.WaitOne() has completed so d could be already set to another value. I tried to insert locks but it resulted into a deadlock. AutoResetEvent e = new AutoResetEvent(false); public SetData(MyData d) { this.d=d; e.Set(); // notify that new data is available } // This runs in separate thread and waits for d to be set to a new value void Runner() { while (true) { e.WaitOne(); // waits for new data to

AutoResetEvent vs. boolean to stop a thread

邮差的信 提交于 2019-11-28 21:33:05
I have an object in a worker thread, which I can instruct to stop running. I can implement this using a bool or an AutoResetEvent: boolean: private volatile bool _isRunning; public void Run() { while (_isRunning) { doWork(); Thread.Sleep(1000); } } AutoResetEvent: private AutoResetEvent _stop; public void Run() { do { doWork(); } while (!_stop.WaitOne(1000)); } The Stop() method would then set _isRunning to false, or call _stop.Set() . Apart from that the solution with AutoResetEvent may stop a little faster, is there any difference between these method? Is one "better" than the other? C#