Bool可由应用程序的多个进程访问
我有多个同时运行的 ac# 控制台应用程序实例。当一个人正在执行一项特定任务时,其他人不应该执行相同的任务。因此,理想情况下,我希望内存中有一些常用的布尔值,所有实例都可以在开始执行该任务之前检查它们。如果布尔为真,他们需要等待。执行任务的进程完成后会将布尔值设置为 false。
我知道“互斥体”存在,但我不确定如何实现它或者它是否是我所需要的。哪个进程在内存中创建了这个变量?其他人如何知道在内存中的哪里可以找到它?
任何帮助将不胜感激。
I have multiple instances of a c# console application running at the same time. While one is performing a specific task, no other one should be performing that same task. So ideally, I'd like to have some commonly accessible bool in memory that all of the instances can check before starting to perform that task. If the bool is true, they need to wait. The process performing the task would set the bool to false when finished.
I know that "mutex" exists, but I'm not sure how to implement it or if it is what I need for this. Which process creates this variable in memory? How do the other ones know where in memory to find it?
Any help would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实现此目的的一种方法是使用互斥体,因为您是跨进程执行此操作,所以您需要使用命名互斥体:
我喜欢使用 guid 作为名称的一部分,以防止与其他应用程序发生命名冲突的任何可能性。
One way to do this is with a Mutex, since you are doing this across processes, you will need to use a named mutex:
I like to use a guid as part of the name, to prevent any possiblity of a naming collision with another app.
您需要使用系统范围的互斥体,您可以通过提供名称来创建。查看构造函数示例 MSDN 页面。
You need to use a system-wide Mutex, which you can create by providing a name. Check out the example for the constructor MSDN page.