这里快速的答案。
某些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