如何在整个 Windows 应用程序 C# 中保持线程处于活动状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1042249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 12:42:31  来源:igfitidea点击:

How to keep thread alive throughout the windows application c#

c#windowsdesktop-application

提问by Anuya

I am using thread which will receive messages from the external application.So my thread shud be alive always.

我使用的线程将从外部应用程序接收消息。所以我的线程应该始终处于活动状态。

I want my thread to be running through out the application, untill application exits. Currently i am calling my thread in program.cs, which is the startup for windows application c#. Please see the code below to know how i am doing it.

我希望我的线程在应用程序中运行,直到应用程序退出。目前我在 program.cs 中调用我的线程,它是 windows 应用程序 c# 的启动。请查看下面的代码以了解我是如何做的。

When i use the below code, the thread starts up when application starts...But it aborts some how, after the thread recieves one message from the external application.

当我使用下面的代码时,线程会在应用程序启动时启动……但是在线程收到来自外部应用程序的一条消息后,它会如何中止一些。

I hope i am clear with my questio. Please help. Thanks.

我希望我清楚我的问题。请帮忙。谢谢。



  static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        StartThread();
        Application.Run(new Screensaver());
    }
    public static void StartThread()
    {
            DeamonEngine Deamon = new DeamonEngine();
            Thread ThreadReciever = new Thread(Deamon.Receiver);
            if (!(ThreadReciever.IsAlive))
            {
                ThreadReciever.Start();
            }
        }
    }


From a comment:

来自评论:

    void Receiver() { 
        try { 
            Initiate socket s; 
            Bind Ip address; 
            s.Receiver[bytes]; 
            Access the members of message received in bytes;
            Assign the members of message to local variable;
            Read Xml File, get the node values and write to batch file; 
            Execute batch file. 
        } 
        catch { } 
    }

回答by Matthew Scharley

Your startup code looks fine: my prognosis is there's something wrong with DaemonEngine.Receiver(), perhaps an exception is being thrown, or perhaps the function itself is structured to only handle a single message... Without seeing the exact function it's hard to say.

您的启动代码看起来不错:我的预测是 有问题DaemonEngine.Receiver(),可能正在抛出异常,或者函数本身的结构可能只处理一条消息……如果没有看到确切的函数,很难说。

EDIT:

编辑:

To get my stuff out of my comments:

从我的评论中获取我的东西:

SOMETHING is going wrong to kill your thread. Exception, logical error, I can't tell you what, because there's no code of what's happening inside your thread, but something is happening. It's nothing to do with the code you've posted already which simply gets the thread running, not keeps it running

某些事情会导致您的线程出错。异常,逻辑错误,我不能告诉你是什么,因为没有代码说明你的线程内部发生了什么,但有些事情正在发生。这与您已经发布的代码无关,它只是让线程运行,而不是让它继续运行

Also, from the code you have posted, you're simply throwing away the fact there was an exception... I don't have a link on hand, but swallowing exceptions like that is horrible. Especially inside a thread where they don't show up like normal anyway.

此外,从您发布的代码中,您只是抛弃了存在异常的事实......我手头没有链接,但是吞下这样的异常是可怕的。尤其是在一个线程中,无论如何它们都不会像平常一样出现。

There's also no indication of a loop of any kind, so it could be one or both of my suggestions above that is causing problems.

也没有任何类型循环的迹象,因此可能是我上面的一个或两个建议导致了问题。

回答by Nader Shirazie

Having a thread execute the Receiver method doesn't mean the thread will repeatedly execute the method.

让线程执行 Receiver 方法并不意味着该线程将重复执行该方法。

Given the processing code in the question, Daemon.Receiverneeds to execute in a loop so that it can go back and retrieve the next message to process. It should look something like this:

给定问题中的处理代码,Daemon.Receiver需要在循环中执行,以便它可以返回并检索下一条要处理的消息。它应该是这样的:

void Receiver() { 
    while(!done) // without this loop, only one execution will occur
    {
        try { 
            // do stuff
        } 
        catch { 
            // log/handle error
        } 

        // wait for next message
    }
}

回答by Hans Malherbe

Typically your DaemonReceiver would have code like this

通常你的 DaemonReceiver 会有这样的代码

while (!quit) 
{
  --- do work ---
  Thread.Sleep(1000);
}

This keeps the thread alive until you set the quitglobal variable in the main thread.

这使线程保持活动状态,直到您quit在主线程中设置全局变量。

Also, it is very important to not let exceptions leak out of your thread. These exceptions will not be reported anywhere and will cause silent errors, probably what you're experiencing now. Do a catch all and at least report on it.

此外,不要让异常从您的线程中泄漏出去也很重要。这些异常不会在任何地方报告,并且会导致无提示错误,可能是您现在遇到的情况。做一个全面的,至少报告它。

回答by Andy White

Your thread might be experiencing a Exception, which is not being caught. Try putting a try-catch in the method that is being executed and see if you're getting an exception.

您的线程可能遇到了未捕获的异常。尝试在正在执行的方法中放置一个 try-catch 并查看是否出现异常。