dotnet 核心相当于 Thread.Abort [英] dotnet core equivalent to Thread.Abort

查看:38
本文介绍了dotnet 核心相当于 Thread.Abort的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Service 抽象.每个服务都有自己的WorkItem.WorkItem 能够从一些数据开始.该服务正在限制 WorkItem 的执行时间.假设单个工作项最多需要 60 秒.在此之后,Service 应该杀死它.

I have a Service abstraction. Each service has it own WorkItem. WorkItem able to start with some data. The service is limiting the excution time of WorkItem. Let's say that a single workitem can takes up to 60 seconds. After this, the Service should kill it.

此代码从标准 .NET Framework 迁移,我创建了一个运行 Start(model) 方法的 Thread 对象.然后代码是这样的:

This code migrated from the Standard .NET Framework, I created a Thread object which run the Start(model) method. Then the code was something like:

Thread t = new Thread(workItem.Start, model);
t.start();
if (!t.Join(TimeSpan.FromSeconds(60)))
    t.Abort();

Thread.Abort 正在为正在运行的线程注入异常,导致它立即停止.

The Thread.Abort was injecting an exception for the running thread, which lead it for immediately stop.

现在,我将代码移至 dotnet 核心 - 正如您所知,当您调用 Thread.Abort() 时,您会收到以下消息:

Now, I moved the code to dotnet core - as you may know, when you calling Thread.Abort() your getting the following message:

System.PlatformNotSupportedException: Thread abort is not supported on this platform.
   at System.Threading.Thread.Abort()
   at ...

目标

我想将 WorkItem 的执行时间限制为特定的时间量.请注意,如果您像这样运行代码行,则此限制也应该起作用:

The Goal

I want to limit the execution time of the WorkItem to specific amount of time. Note that this limitation should work also if you running code line like this:

Thread.sleep(61000); // 61 seconds. should be stop after 60 seconds.

进展

在 dotnet 核心世界上,它似乎要转到 Task 相关的解决方案.所以,我想使用 CancellationToken.但似乎不可能观看Cacneled"事件并立即停止.我看到的例子是使用 while (!canceled) 循环,它不能停止长时间的操作(比如 Thread.Sleep(1000000).

Progress

On the dotnet core world, it's seems like it's going to the Task related solution. So, I thought to use CancellationToken. But its seems like its impossible to watch the "Cacneled" event and stop immediately. The examples I saw are using while (!canceled) loops, which cant stop long operations (like Thread.Sleep(1000000).

如何做对?

我写了这个示例代码:

public static bool ExecuteWithTimeLimit(TimeSpan timeSpan, Action codeBlock)
{
    try
    {
        Task task = Task.Factory.StartNew(() => codeBlock());
        if (!task.Wait(timeSpan))
        {
            // ABORT HERE!
            Console.WriteLine("Time exceeded. Aborted!");
        }
        return task.IsCompleted;
    }
    catch (AggregateException ae)
    {
        throw ae.InnerExceptions[0];
    }
}

还有这个Main文件:

public static void Main(string[] args)
{
    bool Completed = ExecuteWithTimeLimit(TimeSpan.FromMilliseconds(2000), () =>
    {
        Console.WriteLine("start");
        Thread.Sleep(3000);
        Console.WriteLine("end");
    });

    Console.WriteLine($"Completed={Completed}");
    Console.ReadLine();
}

预期:结束"不会打印到屏幕上.实际:打印结束".是否有任何替代方法可以杀死 Task?

Expected: "end" wont be printed to the screen. Actual: "end" printed. Is there any alternative that can kill a Task?

推荐答案

使用线程.中断();而不是 Abort 方法.

Use thread.Interrupt(); instead of Abort method.

这篇关于dotnet 核心相当于 Thread.Abort的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆