在Backgroundworker中启动线程并保持线程可用

时间:2019-07-18 07:07:31

标签: c# multithreading

我在while循环中有backgroundworker,并且在此backgroundworker Thread中,何时尚未启动。 我正在尝试使thread1保持活动状态,并在尚未启动时一次又一次地启动。

我搜索了很多有关线程的主题-由于线程终止,我发现我出错了。

public static void DoWork()
            {
                Console.WriteLine("dowork1");
                Thread.Sleep(1000);
                Console.WriteLine("dowork2");
                Thread.Sleep(1000);
                Console.WriteLine("dowork3");
                Thread.Sleep(1000);
                Console.WriteLine("dowork4");
                Thread.Sleep(1000);
            }

        Thread thread1 = new Thread(DoWork);


        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            while(true)
            {
                Console.WriteLine("Background worker work");
                Thread.Sleep(1000);

                if (thread1.IsAlive == false)
                {

                    try
                    {
                        thread1.Start();
                    }
                    catch { };

                }

            }

        }

运行上述代码时,我的输出是:

Background worker work
Background worker work
dowork1
Background worker work
dowork2
dowork3
Background worker work
Background worker work
dowork4
Wątek 0x1690 zakończył działanie z kodem 0 (0x0).
„WindowsFormsApp6.exe” (CLR v4.0.30319: WindowsFormsApp6.exe): załadowano „C:\Windows\Microsoft.Net\assembly\GAC_MSIL\mscorlib.resources\v4.0_4.0.0.0_pl_b77a5c561934e089\mscorlib.resources.dll”. Moduł został skompilowany bez symboli.
Zgłoszony wyjątek: „System.Threading.ThreadStateException” w mscorlib.dll
Background worker work
Zgłoszony wyjątek: „System.Threading.ThreadStateException” w mscorlib.dll
Background worker work
Zgłoszony wyjątek: „System.Threading.ThreadStateException” w mscorlib.dll
Background worker work
Zgłoszony wyjątek: „System.Threading.ThreadStateException” w mscorlib.dll
Background worker work
Zgłoszony wyjątek: „System.Threading.ThreadStateException” w mscorlib.dll

我只想保留这个重复。并检查thread1不在运行时,再次启动它。 有人可以帮我吗? 请耐心等待。 谢谢! 我需要这样输出:

Background worker work
Background worker work
dowork1
Background worker work
dowork2
dowork3
Background worker work
Background worker work
dowork4
Background worker work
Background worker work
dowork1
Background worker work
dowork2
dowork3
Background worker work
Background worker work
dowork4
Background worker work
Background worker work
dowork1
Background worker work
dowork2
dowork3
Background worker work
Background worker work
dowork4
and forever...

1 个答案:

答案 0 :(得分:2)

From doc:

  

线程终止后,就无法再调用Start来重新启动。

您必须在致电Start之前再次添加它:

console.log("This is an example sentence! Dangit".split(/[\s.?!,]+/));

无论如何,使线程等待后台工作保持活动的正确方法是使其真正保持活动状态,而不是重新启动它。或者,最好使用ThreadPool