简体   繁体   中英

Dynamically create executing code in C#

So, I have strange question (maybe so stupid), but... So, my task. I have same class which gives me same functionality. So, in the main program, which I realize (yes, it's client-server app)) , I want to dynamically create ".exe wrapper" for this class - simplest code like this:

class Program
{
    private SameClass mySameClass;

    static void Main(string[] args)
    {
        mySameClass = new mySameClass(args);
        Console.Readline();
    }
}

In general, I want to create main app which creates slaves in the independent proccesses via dynamically code generation. So, how to make it and control it? Thank you.

So SameClass is supposed to contain the same functions and functionality as the process you want to have run multiple times... I guess what you need are Threads.

Not too sure what you mean by dynamically but let's say you have an event that triggers whenever you need a new SameClass process. Just run

SameClass newClone = new SameClass(args);
Trhead _thread = new Thread(new ThreadStart(newClone.Start));
_trhead.Start();

You can probably do this a little more elegant and refactor within SameClass but it's pretty hard to understand your question, so I guess this is the best I can do you hopefully answer your question.

Found solution based on CodeDom. Yes, It doesn't need reflection, sorry. Code example:

using System;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Diagnostics;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            var compiler = new CSharpCodeProvider();
            var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
            parameters.CompilerOptions = "/platform:x64";
            parameters.GenerateExecutable = true;

            CompilerResults results = compiler.CompileAssemblyFromSource(parameters,
                                    @"using System;
                                     class Program {
                                           public static void Main(string[] args) {
                                           Console.WriteLine(""Hello world!"");
                                           Console.ReadLine();
                                           }
                                      }");

            var testProcess = new Process();
            testProcess.StartInfo.FileName = results.CompiledAssembly.CodeBase;
            testProcess.Start();

            Console.WriteLine("I've run slave!");

            Console.ReadLine();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM