线程中调用第三方DLL,WinForm程序正常,windows服务中调用报“尝试读取或写入受保护的内存。这通常指示其他内存已损坏。”
totoz 2011-09-09 03:43:36 同一个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);的地方报“尝试读取或写入受保护的内存。这通常指示其他内存已损坏。”