c# - 如何中止 CLRThread?
问题描述
我对创建的线程有疑问。当我启动线程时,CPU 使用率变高,使服务器变慢。我想中止这个过程并重新运行它。我正在使用 ClrThread 在使用命名空间的进程中查找方法。如何Thread.Abort()
在 ClrThread 中执行?
这是我的代码。
int _threadCounter = 0;
Thread reminderThread = new Thread(CreateObject);
string startOfThisNamespace = this.GetType().Namespace.ToString().Split('.')[0];
using (DataTarget target = DataTarget.AttachToProcess(System.Diagnostics.Process.GetCurrentProcess().Id, false))
{
ClrRuntime runtime = target.ClrVersions.First().CreateRuntime();
foreach(ClrThread _thread in runtime.Threads.ToList())
{
_threadCounter += 1;
IEnumerable<ClrStackFrame> _stackFrames = _thread.EnumerateStackTrace();
List<ClrStackFrame> _stackRelatedToUs = _stackFrames
.Where(o => o.Method != null && o.Method.ToString().StartsWith(startOfThisNamespace)).ToList();
if (_stackRelatedToUs.Count > 0)
{
foreach (var s in _stackRelatedToUs)
{
string _methodName = s.Method.Name;
if (_methodName == "CreateObject")
{
if (_thread.IsAlive)
{
//_thread.Abort(); Like This!!!
}
}
reminderThread.Start();
}
}
else
{
if (_threadCounter == runtime.Threads.Count())
{
if (!reminderThread.IsAlive){
reminderThread.Start();
}
}
}
}
}
谢谢你和问候。
解决方案
这是给你的一个小例子
using System;
using System.Threading;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
using (CancellationTokenSource source = new CancellationTokenSource())
{
CancellationToken token = source.Token;
token.Register(Notify);
new Thread(Worker).Start(token);
Console.WriteLine("Press a key to abort the thread");
Console.ReadLine();
source.Cancel();
//wait 5 seconds for the thread to abort
source.Token.WaitHandle.WaitOne(5000, true);
}
}
/// <summary>
/// callback to do stuff when thread is cancelled
/// </summary>
static void Notify()
{
Console.WriteLine("thread is cancelled");
}
/// <summary>
/// worker thread
/// </summary>
/// <param name="token"></param>
static void Worker(object token)
{
CancellationToken _token = (CancellationToken)token;
do
{
Console.WriteLine("thread is working....");
Thread.Sleep(1000); //pretend I'm doing work
} while (!_token.IsCancellationRequested);
}
}
}
推荐阅读
- ruby-on-rails - RSpec Rails 邮件期望 - 最后一次交付是特定的操作/方法/模板
- php - laravel ORM 模型在所有请求中显示相同的值
- android - 如何通过点击FCM收到的通知进入指定活动?
- javascript - PHP/HTML/JavaScript - 创建具有从 PHP 到 HTML/JavaScript 的数据属性的按钮
- python - 在 NPV 和 IRR 的 Python Newton-Raphson 算法中使用循环
- firebase - Firebase 存储加载图像速度
- flutter - 在颤动中洗牌选项的位置
- database - 云数据库或身份验证服务是否被视为外部因素?(C4 型号)
- heroku - Testdriven.io 课程问题:Flask-TDD Heroku Deployment issue with POST no such app
- javascript - 尝试在另一个带有 Id 的特定“h1”之前插入“h1”