c# - 检测线程已在 C# .net 中运行?

标签 c# .net

我正在使用以下代码。

public void runThread(){
    if (System.Diagnostics.Process.GetProcessesByName("myThread").Length == 0)
    {
    Thread t = new Thread(new ThreadStart(go));
    t.IsBackground = true;
    t.Name = "myThread";
    t.Start();
    }
    else
    {
      System.Diagnostics.Debug.WriteLine("myThreadis already Running.");
    }   
}
public void go()
{
    //My work goes here
}

我多次调用 runThread() 函数,但我希望线程仅在线程未运行时启动。怎么可能?

最佳答案

GetProcessesByName 不会在您的应用程序中查找线程,而是在您的机器中查找进程。事实上,在您自己的应用程序中没有很好的方法来查询线程(一个问题是编写调试器)。

对于你想要的,你可以创建一个 wrapper class for your threads这样您就可以查询它们是否正在运行。或者 keep track of the threads yourself by other means .

您也可以考虑使用 Lazy<Thread>需要时会初始化的字段,可以查询线程是否存活。 测试后Lazy<Thread>这不是一个好主意。


源自 Simon's answer :

private int running;

public void runThread()
{
    if (Interlocked.CompareExchange(ref running, 1, 0) == 0)
    {
        Thread t = new Thread
        (
            () =>
            {
                try
                {
                    go();
                }
                catch
                {
                    //Without the catch any exceptions will be unhandled
                    //(Maybe that's what you want, maybe not*)
                }
                finally
                {
                    //Regardless of exceptions, we need this to happen:
                    running = 0;
                }
            }
        );
        t.IsBackground = true;
        t.Name = "myThread";
        t.Start();
    }
    else
    {
        System.Diagnostics.Debug.WriteLine("myThreadis already Running.");
    }   
}

public void go()
{
    //My work goes here
}

*: Gotta catch'em all


WajidSegey是对的。您可以只拥有一个 Thread 字段。请允许我举个例子:

private Thread _thread;

public void runThread()
{
    var thread = _thread;
    //Prevent optimization from not using the local variable
    Thread.MemoryBarrier();
    if
    (
        thread == null ||
        thread.ThreadState == System.Threading.ThreadState.Stopped
    )
    {
        var newThread = new Thread(go);
        newThread.IsBackground = true;
        newThread.Name = "myThread";
        newThread.Start();
        //Prevent optimization from setting the field before calling Start
        Thread.MemoryBarrier();
        _thread = newThread;
    }
    else
    {
        System.Diagnostics.Debug.WriteLine("myThreadis already Running.");
    }
}

public void go()
{
    //My work goes here
}

注意:最好使用第一个备选方案(源自 Simon 的回答),因为它是线程安全的。也就是说,如果有多个线程同时调用 runThread 方法,则不会有创建多个线程的风险。

关于c# - 检测线程已在 C# .net 中运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12949024/

相关文章:

c# - Raspberry Pi+MonoDevelop如何从串口读取数据?

c# - 在 32 位版本的 Windows (Teamcity) 上编译 x64

c# - firefox 中未捕获的异常

.net - 数据库表复制指南

c# - SQLServer AlwaysOn 和 .net SqlConnection 重置

.net - 在 .NET 中,您可以设置对象的 GC 生成,或者以其他方式指示它即将超出范围吗?

.Net xsd.exe 工具不会生成所有类型

c# - 从 SELECT 语句生成 CREATE TABLE 脚本

c# - 自定义字符串作为 Entity Framework 的主键

c# - Application Insights 不会将带有附加异常对象的 log4net 日志消息发送到 Azure