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

时间:2015-09-14 13:26:38

标签: c# multithreading

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

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

    }

我想' readall'即使执行该功能,也要继续(永久或直到应用程序关闭)。可能吗?因为对我来说,即使满足真实条件,线程也会立即停止。请详细说明。

2 个答案:

答案 0 :(得分:1)

好的,这里稍微修改了你的代码以包含循环。

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,则将退出该流程。

答案 1 :(得分:0)

以下是您要求的示例

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");
        }
    }
}