.NET Core equivalent to Thread.Abort(等同于线程的.NET核心。中止)
问题描述
背景
我有一个Service
抽象。每个服务都有自己的WorkItem
。能够从一些数据开始的工作项。该服务正在限制WorkItem
的执行时间。假设单个工作项最多需要60秒。在此之后,Service
应该会杀死它。
此代码从.NET框架迁移而来,我创建了一个运行Start(model)
方法的Thread
对象。然后代码类似于:
Thread t = new Thread(workItem.Start, model);
t.start();
if (!t.Join(TimeSpan.FromSeconds(60)))
t.Abort();
Thread.Abort
正在为正在运行的线程注入异常,导致其立即停止。
现在,我将代码移到DotNet core-如您所知,当您调用Thread.Abort()
时,收到以下消息:
System.PlatformNotSupportedException: Thread abort is not supported on this platform.
at System.Threading.Thread.Abort()
at ...
目标
我希望将WorkItem
的执行时间限制为特定的时间量。请注意,如果您运行如下代码行,则此限制也应该起作用:
Thread.Sleep(61000); // 61 seconds. should be stop after 60 seconds.
进度
在DotNet的核心世界中,它似乎要走向Task
相关的解决方案。所以,我想用CancellationToken
。但看着被取消的活动并立即停止似乎是不可能的。我看到的例子是使用while (!canceled)
循环,它不能停止长操作(如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();
}
预期:将不会打印到屏幕上。实际:&Q;结束&Q;打印。有没有其他方法可以杀死Task
?
推荐答案
使用线程。中断();而不是Abort方法。
这篇关于等同于线程的.NET核心。中止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:等同于线程的.NET核心。中止


- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04