Reputation: 170499
I have a .NET class library that has a class with a static method. I want my code to run that static method in a separate process - the same way I'd run it in a separate thread just in a separate process.
I know I can create a separate console application project call the static method from inside Main()
but that's not convenient for my deployment scenario - I'd rather not carry an extra .exe file around. I know I can use Powershell to invoke it but that would mean being dependent on Powershell which I'd rather avoid.
Is there a way to run code in a separate process using .NET only? Maybe I could create the executable for that separate process during runtime?
Upvotes: 36
Views: 25546
Reputation: 39833
Unfortunately, you cannot fork
in C# like you can in C on POSIX-compatible operating systems.
You have a few options. Since you're just looking to protect against infinite loops, you could just spawn a new Thread
(a new one, not a ThreadPool
one or a Task
one). Then, you can call Abort
on the thread if you need to kill it. This will trigger a ThreadAbortException
in the other thread.
Your other option is an AppDomain
. You can create a new AppDomain
using the currently running assembly relatively trivially. Then, you make a call into a proxy object that actually exists across the domain. The proxy will use old-school .NET remoting to call the method on the real object (so no generic-passing, etc., since you're limited by .NET 1.1-based constructs).
Be aware that none of the above strategies will protect you from a crash in unmanaged code. Since AppDomains are a managed construct, you cannot use them to abort unmanaged hang-ups.
If you're really, really, really determined to get a second OS-level process, you can also generate a new executable assembly in a temporary file on the fly and start that in a new process. See here for an MSDN article on new assembly generation. Be aware that this is not trivial at all.
Upvotes: 32