Single instance app with message passing via cmd line?

橙三吉。 提交于 2020-01-05 04:24:24

问题


I have a C# app that is launched via command line. Usually data is pass through the command line such as add (app -a string). I would like only ONE instance of the app to be opened and if more strings are added via command line i would like the single instance to know about it and update itself. I can either put the data into the database properly and msg the running instance or msg and pass the data to the running instance and let it put it in the db and update itself.

How would i do this in C# .NET? (3.5)


回答1:


The first instance of the application should create a named pipe, subsequent instances of the application would fail to create the same named pipe and should instead attempt to open the named pipe for use. Once opened, the string (or really any data) can be transferred to the already running instance of the app. The named pipe can then be closed and the app could exit.

Alternatively, you could use .NET Remoting and register a well-known type that other instances of the application could activate, with behavior similar to what is described above.

Ultimately, a quick search on "IPC" or "Inter-Process Communication" may open up other alternatives. But I believe the named pipe approach is the cleanest and would be the easiest to implement/extend.

For "first-run" detection you can also create a named mutex, in case you opt for an IPC mechanism that doesn't exhibit a failure condition on multiple-runs (for example, using a database as a middle-man for data share). No two processed can "Create" a mutex with the same name, this is the same constraint as with Named pipes, as these names are managed by the Kernel (and thus span process, session, desktop and window station boundaries.)



来源:https://stackoverflow.com/questions/1685005/single-instance-app-with-message-passing-via-cmd-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!