首页 > 解决方案 > 查找特定线程并访问其方法 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

标签: c#multithreadingasp.net-core

解决方案


首先,这是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


推荐阅读