繁体   English   中英

即使函数终止,也触发无限线程

[英]Trigger an endless Thread Even when the Function Terminates

问题是,当函数已经执行并且线程在该函数中启动时,线程会发生什么。 (请看下面的例子)

    public int Intialise ()
    {
        int i = startServer();
        Thread readall = new Thread(readAllMessage);
        if (i == 1)
            readall.Start();
        else
            MessageBox.Show("Connection Error");
        return i;

    }

即使执行了该函数,我也希望“readall”继续(永远或直到应用程序关闭)。 是否可以? 因为对我来说,即使满足真实条件,线程也会立即停止。 请说明一下。

好的,这是您的代码稍作修改以包含循环。

internal class Program
    {
        public static int Intialise()
        {
            int i = startServer();
            Thread readall = new Thread(readAllMessage);
            readall.IsBackground = true; // so that when the main thread finishes, the app closes
            if (i == 1)
                readall.Start();
            else
                Console.WriteLine("Error");
            return i;
        }

        public static void readAllMessage()
        {
            while (true)
            {
                Console.WriteLine("reading...");
                Thread.Sleep(500);
            }
        }

        public static int startServer()
        {
            return 1;
        }


        private static void Main(string[] args)
        {
            var i = Intialise();
            Console.WriteLine("Init finished, thread running");
            Console.ReadLine();
        }
    }

当你运行它时,它会打印:

Init finished, thread running
reading...
reading...
reading...

当您按 Enter 键时(请参阅Console.ReadLine() )它将停止运行。 如果您将IsBackground更改为TRUE ,它将不会退出该过程。

这是你问的一个例子

using System; 
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ForeverApp
{

    class SomeObj
    {
        public void ExecuteForever()
        {
            while (true)
            {
                Thread.Sleep(1000);
                Console.Write(".");
            }
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            SomeObj so = new SomeObj();

            Thread thrd = new Thread(so.ExecuteForever);

            thrd.Start();

            Console.WriteLine("Exiting Main Function");
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM