jjzjj

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

coder 2024-06-09 原文

我有一个简单的 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/

有关c# - Windows 服务错误 : "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."的更多相关文章

随机推荐