c# - 查找特定线程并访问其方法 C#
问题描述
我试图通过查询线程列表中的线程threadId
并访问该特定线程中的函数。
因此,当用户从前端输入价格时,它将执行CreateThread()
并创建一个新线程并将其添加到线程列表中。
List<Thread> lstThreads = new List<Thread>();
public static Thread Start(MyClass myClass) {
Thread thread = new Thread(() => { myClass(); });
thread.Start();
return thread;
}
public IActionResult CreateThread(int price)
{
var thread = Start(new MyClass(DoWork(price)));
lstThreads.Add(thread);
}
public class MyClass
{
bool stop = false;
private void DoWork(int price)
{
while(!stop)
{
// Do work here
}
if (stop) return;
}
public void Stop()
{
lock (stopLock) {
stop = true;
}
}
}
当线程的用户现在想DoWork()
通过调用来停止 while 循环时Stop()
,如何做到这一点?顺便说一句,用户知道threadId
。
解决方案
首先,这是1999年的做法。如果您有能力使用任务和/或异步/等待,请使用它们!它们的效率要高得多。现在,如果您必须使用线程,您可以在 MyClass 中创建/启动线程并保留对它的引用,然后调用 Stop :
public class MyClass
{
private volatile bool stop = false;
private volatile int price;
private Thread myThread;
public MyClass(int price)
{
this.price = price;
myThread = new Thread(DoWork);
}
public void DoWork()
{
while(!stop)
{
// Do work here
}
if (stop) return;
}
public void Stop()
{
stop = true;
}
}
...
List<MyClass> lstMyThreads = new List<MyClass>();
foreach (var myT in lstMyThreads)
myT.Stop();
但我需要再说一遍:如果可能,请使用 Tasks 和 CancellationToken。
推荐阅读
- javascript - 我想将我的数据添加到 Angular 中的 ui
- android - 无法通过 facebook 在应用中注册
- ios - 如何在 Google Autocomplete iOS 中仅获取印度城市名称?
- swift - 如何修复 viewDIdLoad 中的 indexPath 错误?
- azure - FileTrigger 绑定不解析
- php - 如何用逗号分隔字符串并存储在字符串中
- fancybox - 保持箭头可见
- reporting-services - Converting * character in SSRS Expression
- c# - 根据元素值对列表进行排序
- python - 如何从另一个 python 文件导入和获取变量?