Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I run C# code in a separate process without crafting a console application?

Tags:

c#

.net

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?

like image 223
sharptooth Avatar asked Oct 18 '12 10:10

sharptooth


People also ask

Can I run C language?

Step 1: Open turbo C IDE(Integrated Development Environment), click on File and then click on New. Step 2: Write the C program code. Step 3: Click on Compile or press Alt + F9 to compile the code. Step 4: Click on Run or press Ctrl + F9 to run the code.

Can you run C anywhere?

Although C program cannot be compiled once and run "everywhere", but Intel and AMD processors are really the same place in this sense.

Can I run C in CMD?

We usually use a compiler with a graphical user interface, to compile our C program. This can also be done by using cmd. The command prompt has a set of steps we need to perform in order to execute our program without using a GUI compiler.


1 Answers

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.

like image 112
David Pfeffer Avatar answered Oct 05 '22 16:10

David Pfeffer