這裏快速的答案。
某些DLL與啓動它的第一個線程有親和力。我過去所做的就是讓該線程在後臺保持活動狀態,並帶有一個循環。然後您偵聽該DLL加載的線程中的事件。您可能需要重構代碼以偵聽事件,而不是調用DLL調用。
希望有幫助嗎?
我已經添加了一些示例代碼,您可以嘗試一下,看看會發生什麼。它不完美,但它應該有助於說明如何保持線程活着。還有其他方法可以做到這一點,但我只想保持示例簡單
using System;
using System.Reflection;
using System.Threading;
namespace ConsoleApplication3
{
internal class Program
{
private static void Main(string[] args)
{
var newThread = new Thread(DllLoader.DoWork);
newThread.Start();
//My other application Logic
}
public class DllLoader
{
public enum ThingsICanDo
{
Jump,
Duck,
Run,
Quit
}
private static bool appStillRunning;
private static object myInstanceDllType;
private static void CheckForStuffToDo()
{
//Much better to use events, and pass the message inthe event
// then do what the message wants, and but I am keeping this breif
// for this example.
var DoNext = (ThingsICanDo) Enum.Parse(typeof (ThingsICanDo), Console.ReadLine(), true);
switch (DoNext)
{
case ThingsICanDo.Jump:
//Do jump stuff
Console.WriteLine("Jump");
//myInstanceDllType.JumpStuff();
break;
case ThingsICanDo.Duck:
Console.WriteLine("Duck");
//myInstanceDllType.DuckStuff();
//Do duck stuff
break;
case ThingsICanDo.Run:
Console.WriteLine("Run");
//myInstanceDllType.RunStuff();
//Do run stuff
break;
case ThingsICanDo.Quit:
//Do exit stuff
Console.WriteLine("Bye");
Thread.CurrentThread.Abort();
break;
}
}
public static void DoWork()
{
var externalAssembly = Assembly.LoadFrom("/path/my.Dll");
myInstanceDllType = Activator.CreateInstance("DLLTypeINeed");
while (appStillRunning)
{
try
{
CheckForStuffToDo();
}
catch (Exception e)
{
//Log e
Console.WriteLine(e);
}
Thread.Sleep(1000);
//Much better to use semaphore.wait or something similar, but this is a simple example
}
}
}
}
}
你能分享一下你試過的嗎 –
什麼是你正在加載的DLL –
我正在複製我的DLL到exe文件夾位置 – kaviarasan