简体   繁体   English

在.NET Core中强制线程停止

[英]Force thread stop in .NET Core

Let's say i have .NET Core 2.0/2.1 program. 假设我有.NET Core 2.0 / 2.1程序。 There is a thread executing the following method. 有一个线程执行以下方法。 I want to stop it forcefully. 我想强行停止它。

Important notes: 重要笔记:

Cooperative multitasking (for example, with CancellationToken) is a good thing, but not the case 协作式多任务处理(例如,使用CancellationToken)是一件好事,但并非如此

XY problem ( https://en.wikipedia.org/wiki/XY_problem ) does exist, but i just want to know if stopping this thread is actually possible XY问题( https://en.wikipedia.org/wiki/XY_problem )确实存在,但我只想知道是否确实有可能停止此线程

while (true)
{
    var i = 0;
    try
    {
        Console.WriteLine($"Still alive {i++}");
    }
    catch (Exception e)
    {
        Console.WriteLine($"Caught {e.GetType().Name}");
    }
}

Tried several options: 尝试了几种选择:

Concerns, from most important to least: 关注点,从最重要到最不重要:

  • Releasing locks 释放锁
  • Disposing objects in using directives 使用指令处理对象
  • Actually collecting allocated objects 实际收集分配的对象

(as a corner case we can assume that out thread does not perform any heap allocations at all) (作为一个特例,我们可以假设out线程根本不执行任何堆分配)

Use a ManualResetEventSlim . 使用ManualResetEventSlim The instance will need to be available to both the thread you are trying to stop and the thread which will cause the stop. 该实例将对您要停止的线程和将导致停止的线程都可用。

In your while(true) loop, do something like this: 在您的while(true)循环中,执行以下操作:

var shouldTerminate = mres.Wait(100);
if (shouldTerminate) { break; }

What this does is wait until the ManualResetEvent is put into a Set state, or 100ms, whichever comes first. 这是要等到ManualResetEvent进入Set状态或100ms后(以先到者为准)。 The value returned indicates if the event is Set or Unset. 返回的值指示事件是Set还是Unset。 You'll start off with the MRE in an Unset state, and when the control thread wishes to terminate the worker thread, it will call the Set method, and then it can Join the worker thread to wait for it to finish. 您将从MRE处于Unset状态开始,当控制线程希望终止工作线程时,它将调用Set方法,然后可以加入工作线程以等待其完成。 This is important as in your loop you could perhaps be waiting on a network call to finish, and the worker won't actually terminate until you are back at the top of the loop again. 这很重要,因为在您的循环中,您可能正在等待网络调用完成,并且直到您再次回到循环的顶部,工作线程才真正终止。 If you need to, you could check the MRE with Wait at multiple points in the worker thread to prevent further expensive operations from continuing. 如果需要,可以在辅助线程中的多个点上单击“等待”来检查MRE,以防止继续进行进一步的昂贵操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM