gpt4 book ai didi

c# - Windows 服务错误 : "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

转载 作者:可可西里 更新时间:2023-11-01 09:57:10 25 4
gpt4 key购买 nike

我有一个简单的 Windows 服务应用程序,我试图在 VS 2008 IDE 中调试,但每次运行代码时,我都会收到错误 “尝试读取或写入 protected 内存。这通常表明其他内存已损坏。” .此错误发生在下面的 service.Stop() 行:

static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
ServiceBase[] servicesToRun;
servicesToRun = new ServiceBase[]
{
new Service1()
};

if (Environment.UserInteractive)
{
Type type = typeof(ServiceBase);
BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
MethodInfo method = type.GetMethod("OnStart", flags);

foreach (ServiceBase service in servicesToRun)
{
method.Invoke(service, new object[] { args });
}

Console.WriteLine("Press any key to exit");
Console.Read();

foreach (ServiceBase service in servicesToRun)
{
service.Stop();//ERROR OCCURS HERE!
}

}
else
{
ServiceBase.Run(servicesToRun);
}
}
}

下面是简单的windows服务类

public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}

protected override void OnStart(string[] args)
{
}

protected override void OnStop()
{
}
}

最佳答案

如果你想在 ServiceBase.Run() 之外完全管理启动 ServiceBase,那么你也应该用同样的技巧来停止它:

MethodInfo stopMethod = type.GetMethod("OnStop", flags); 

foreach (ServiceBase service in servicesToRun)
{
stopMethod.Invoke(service, new object[] { args });
}

关于c# - Windows 服务错误 : "Attempted to read or write protected memory. This is often an indication that other memory is corrupt.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/785732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com