Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a message to another exe from an exe C#

Tags:

c#

ipc

I have two exe running, C# console programs. From one, I need to tell the second exe to do something? How can I do this? I looked at

(Remotable.CommonAssembly)Activator.GetObject(typeof(Remotable.CommonAssembly)

but from here I can call a method of the CommonAssembly(referenced dll) not the exe one's.

like image 257
Samir Avatar asked Dec 13 '22 04:12

Samir


1 Answers

For simple scenarios a plain old windows event would be enough - a program waits to be signaled to do something.

Spawn a thread in the waiting program that waits for the event.

//Program 1

EventWaitHandle evt = OpenOrCreateEvent("Global\\MyEvent");
evt.WaitOne(); // this thread will block waiting without wasting CPU cycles, 
               // it will be be signaled from the kernel 
               // when the event is set
DoStuff();


//Program 2

EventWaitHandle evt = OpenOrCreateEvent("Global\\MyEvent");
evt.Set();

Take a look at the EventWaitHandle, ManualResetEvent, AutoResetEvent classes.

  • Consider which program is going to create the event - you could try to open the event from both programs, if it doesn't exist than create it.
  • Prefix the event name with 'Global\' if one of the programs is a service ( and/or running in other session/user). Otherwise it won't work on Vista or later.
  • When creating the event you may need to set security attributes so it can be opened from other processes from other sessions.

Advanced IPC mechanisms like WCF, Remoting, DCOM, CORBA, etc may be better if you have more complicated communication protocol with different actions to trigger, return values and so on. For simple cases (a couple) of windows events would be enough.

Notice If you need to transfer data between your processes consider memory mapped files. "Official" .NET classes for them will be available with .NET 4.0, currently you can use http://github.com/tomasr/filemap/tree/master

like image 191
devdimi Avatar answered Dec 21 '22 23:12

devdimi