线程中调用第三方DLL,WinForm程序正常,windows服务中调用报“尝试读取或写入受保护的内存。这通常指示其他内存已损坏。”

totoz totoz 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
同一个DLL,实现同一个功能,在WinForm中使用计时器或Thread调用都正常,但是在windows服务中调用一直报“尝试读取或写入受保护的内存。这通常指示其他内存已损坏。”

郁闷的是,如果windows服务中取消线程直接调用也正常,希望大家帮我看下,代码入下:

public AlarmEvent()
{
InitializeComponent();

timerReAlarm = new System.Timers.Timer(20* 1000);//秒
timerReAlarm.Elapsed +=new ElapsedEventHandler(timerReAlarm_Elapsed);
timerReAlarm.AutoReset = true;
}

private void timerReAlarm_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
timerReAlarm.Stop();
ThreadPool.QueueUserWorkItem(new WaitCallback(ExecuteTask), null);
timerReAlarm.Start();
}

/// <summary>
/// 开始执行任务
/// </summary>
private void ExecuteTask(object status)
{
TMsgCongestion.MsgAction();
}

---------------------------------------------------------------------------------------以下是调用DLL的部分
[DllImport("kernel32.dll", EntryPoint = "LoadLibrary")]
public static extern int LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpLibFileName);

[DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]
public static extern IntPtr GetProcAddress(int hModule, [MarshalAs(UnmanagedType.LPStr)] string lpProcName);

delegate int Sends([MarshalAs(UnmanagedType.LPStr)]string par1, int par2);

Sends sends;
public void MsgAction(string content)
{
int hmodule = LoadLibrary("SSMQ2Client.dll");
IntPtr intPtrSends = GetProcAddress(hmodule, "sends");
sends = (Sends)Marshal.GetDelegateForFunctionPointer(intPtrSends, typeof(Sends));

sends(content,300);
}


每次就会在执行到 sends(content,300);的地方报“尝试读取或写入受保护的内存。这通常指示其他内存已损坏。”
...全文

相关推荐

评论 14
收藏 已收藏
分享
返回顶部
totoz
C# 111,129 成员 642,539 内容