C # Kill all threads

I have an application that calls my DLL using InvokeMember() as follows:

 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; } } 

My DLL creates a new thread and starts processing. In my DLL, I create a new thread as follows:

 Thread thread = new Thread( delegate(){ while(true) { GetFilesInFolder(); Thread.Sleep(120000); } }); ne.Start(); 

The goal is to periodically check the folder. The problem is that when I close the application that calls my DLL, the process does not close. Is there a way to close all threads?

NB: I cannot change the application, I can only change my DLL.

+6
source share
4 answers

Set the IsBackground property of the stream to true . This will destroy the thread when your application ends.

Also: Why don't you use one timer (or just one thread) that wakes up and excludes data. This should be more resource friendly.

+8
source

Have you tried to use System.IO.FileSystemWatcher ? this triggers events when something changes in the folder. It seems like this will simplify your decision.

+6
source

How about introducing secure cancellation from here

 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(); } } 

Test

 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(); } } 
+1
source

You can use the background thread mentioned above or a timer:

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

Do not forget to dispose of it.

0
source

Source: https://habr.com/ru/post/904979/


All Articles