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 in开发者_开发技巧to 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)
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.)
精彩评论