英文:
Pause all other threads while one thread is working in C# and resume after the work is done by that thread
问题
I need to trigger a function when a desired condition meets. That function can be triggered from different threads via different event handlers. The issue arises when I need to call the same function from multiple threads simultaneously due to concurrent event handlers. I am modifying a value within that function, but it's not working correctly when multiple event handlers trigger the function simultaneously. Is there a way to temporarily halt other threads from triggering the same function until the currently executing thread finishes? I am using a Windows Forms application with .NET Framework 4.8. I tried using thread.Sleep
, but it doesn't meet my requirements. Is there an alternative approach?
英文:
I am working on a code in which I need to trigger a function when a desired condition meets. That function can be triggered from different different threads parallelly via different event handlers. Problem starts when I need to call same function from two or more threads at the same time due to multiple event handlers triggering at the same time. I am making some changes in the value in that function and then returning back to a different class and this is not working properly since one of the event handler triggering that function is over-riding the other value in case the function is being triggered at the same time. Is there a way to pause all the other threads triggering that same function until the thread working on that particular function completes processing. I am using Windows form application with .net framework 4.8.
I have tried using thread.Sleep method but that's not what I needed. Is there any other way?
答案1
得分: 2
听起来你想要一个锁定。这将确保代码的某些部分只能由一个线程运行,通常称为临界区。任何其他尝试获取相同锁的线程将被暂停,或阻塞,直到第一个线程释放锁。
如果锁对你来说是新的,我强烈建议在花更多时间研究线程安全之前避免任何类型的多线程开发。多线程是困难的,许多错误可能难以重现。这不是适合试错的领域。
英文:
It sounds like you want a lock. This will ensure some section(s) of code can only be run by a single thread at a time, usually called a critical section. Any other thread trying to take the same lock will be paused, or blocked until the first thread releases the lock.
If locks are new to you I would highly recommend avoiding any type of multi threaded development until you have spent a bit more time studying thread safety. Multi threading is difficult, and many errors can be difficult to reproduce. This is not an area where trial and error is appropriate.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论