所以发生了什么是我的控制台程序打开然后从文本文件运行外部c#程序/代码.这一切都运行良好,但当我关闭原始窗体窗口时,它执行的程序/代码也关闭.有没有办法阻止我从关闭运行的文本文件代码?
这是它调用运行程序的代码
static void MemExe(byte[] buffer)
{
Assembly asm = Assembly.Load(buffer);
if (asm.EntryPoint == null)
throw new ApplicationException("No entry point found!");
MethodInfo ePoint = asm.EntryPoint;
ePoint.Invoke(null, null);
}
Run Code Online (Sandbox Code Playgroud)
其中缓冲区是以字节为单位的代码/程序
这是我的主要
static void Main(string[] args)
{
var data = File.ReadAllText(@"program.txt");
MemExe(data);
}
Run Code Online (Sandbox Code Playgroud)
解决方法是将项目的Output type输入Project's Properties -> Application -> Output type从控制台应用程序更改为Windows 应用程序(请参见屏幕截图)

这样就不会创建控制台窗口,因此该进程既不会显示为两个正在运行的进程,也不会通过关闭控制台窗口来终止它。
这就是我要采取的方法。您的方法在非后台线程中执行,一旦主线程终止,该线程就可以防止进程终止。但是,您仍然无法关闭控制台窗口。这就是为什么我建议切换到Windows Application
using System;
using System.IO;
using System.Reflection;
using System.Threading;
namespace StackOverflow
{
public static class Program
{
static void Main(string[] args)
{
RunExternalFunctionThread t = new RunExternalFunctionThread(File.ReadAllBytes(@"program.txt"));
t.Run();
}
private class RunExternalFunctionThread
{
private Byte[] code;
public RunExternalFunctionThread(Byte[] code)
{
this.code = code;
}
public void Run()
{
Thread t = new Thread(new ThreadStart(this.RunImpl));
t.IsBackground = false;
t.Priority = ThreadPriority.Normal;
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
private void RunImpl()
{
Assembly asm = Assembly.Load(this.code);
if (asm.EntryPoint == null) throw new ApplicationException("No entry point found!");
MethodInfo ePoint = asm.EntryPoint;
ePoint.Invoke(null, null);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
983 次 |
| 最近记录: |