c#杀死所有线程

本文关键字:线程 | 更新日期: 2023-09-27 18:19:22

我有一个应用程序用InvokeMember()调用我的DLL,像这样:

Assembly OCA = Assembly.LoadFrom("./Modules/ProcessFiles.dll");
Type[] types = OCA.GetTypes();
foreach (var type in types)
{
    //MethodInfo[] methods = type.GetMethods();
    if (type.Name == "Converter")
    {
        var tmpType = type;
        var obj = Activator.CreateInstance(tmpType);
        Thread t = new Thread(
            () =>
            tmpType.InvokeMember("Run", BindingFlags.Default | BindingFlags.InvokeMethod, null, obj,
            null));
        t.Start();
        break;
    }
}
我的DLL然后创建一个新的线程并开始处理。在我的DLL中,我像这样创建新线程:
Thread thread = new Thread(
    delegate(){
        while(true)
        {
            GetFilesInFolder();
            Thread.Sleep(120000);
        }
    });
ne.Start();

目的是定期检查文件夹。问题是,当我关闭调用DLL的应用程序时,进程并未关闭。有没有办法关闭所有的线程?

注意:我不能修改应用程序,我只能修改我的DLL。

c#杀死所有线程

设置线程的IsBackground属性为true。这将在你的应用程序结束时杀死线程。

Also:为什么不使用一个计时器(或者只有一个线程)来唤醒和检查数据呢?

您是否尝试使用System.IO.FileSystemWatcher?当文件夹中的某些内容发生更改时,会引发事件。看起来这将简化您的解决方案。

如何从这里实现安全取消

class RulyCanceler
{
  object _cancelLocker = new object();
  bool _cancelRequest;
  public bool IsCancellationRequested
  {
    get { lock (_cancelLocker) return _cancelRequest; }
  }
  public void Cancel() { lock (_cancelLocker) _cancelRequest = true; } 
  public void ThrowIfCancellationRequested()
  {
    if (IsCancellationRequested) throw new OperationCanceledException();
  }
}

测试
class Test
{
  static void Main()
  {
    var canceler = new RulyCanceler();
    new Thread (() => {
                        try { Work (canceler); }
                        catch (OperationCanceledException)
                        {
                          Console.WriteLine ("Canceled!");
                        }
                      }).Start();
    Thread.Sleep (1000);
    canceler.Cancel();               // Safely cancel worker.
  }
  static void Work (RulyCanceler c)
  {
    while (true)
    {
      c.ThrowIfCancellationRequested();
      // ...
      try      { OtherMethod (c); }
      finally  { /* any required cleanup */ }
    }
  }
  static void OtherMethod (RulyCanceler c)
  {
    // Do stuff...
    c.ThrowIfCancellationRequested();
  }
}

你可以使用上面提到的后台线程或定时器:

Timer checkTimer;
public void StartTimer()
{
    checkTimer = new Timer(s => GetFilesInFolder(), null, 0, 120000);
}

别忘了把它处理掉