C#重复执行线程,直到满足条件

时间:2020-02-20 11:33:59

标签: c# multithreading

我是C#和线程的新手,我想了解如何使用它们。

我想做什么:

(1):我希望3个不同的功能同时开始工作。每个函数都有一个分配的线程和一个睡眠时间。

(2):重复(1)5次。

我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Threading;

namespace ThreadMultiples
{
    class Program
    {
        static void Main(string[] args)
        {


            int i = 0;

            do
            {
                threads();
                i += 1;
                Console.WriteLine($"i == {i}");
            } while (i < 5);


            Console.WriteLine("End Main");
        }//End Main


        static void hola()
        {
            Console.WriteLine($"Time in hola: {DateTime.Now.ToString("hh:mm:ss")}");
            Console.WriteLine("hola");
            Thread.Sleep(1000);
            Console.WriteLine($"Time out hola: {DateTime.Now.ToString("hh:mm:ss")}");
        }//End hola
        static void hello()
        {
            Console.WriteLine($"Time in hello: {DateTime.Now.ToString("hh:mm:ss")}");
            Console.WriteLine("hello");
            Thread.Sleep(3000);
            Console.WriteLine($"Time out hello: {DateTime.Now.ToString("hh:mm:ss")}");
        }//End hello

        static void add()
        {
            Console.WriteLine($"Time in add: {DateTime.Now.ToString("hh:mm:ss")}");
            Console.WriteLine("add");
            Thread.Sleep(5000);
            Console.WriteLine($"Time out add: {DateTime.Now.ToString("hh:mm:ss")}");
        }//End add

        static void threads()
        {
            Console.WriteLine($"Time in THREADS: {DateTime.Now.ToString("hh:mm:ss")}");
            var th_hola = new Thread(hola);
            var th_hello = new Thread(hello);
            var th_add = new Thread(add);

            th_hola.Start();
            th_hello.Start();
            th_add.Start();

            Console.WriteLine($"Time out THREADS: {DateTime.Now.ToString("hh:mm:ss")}");
        }// End threads()

    }//End class

}//End namespace

Console Output

如您所见,我在“ End Main”之后得到“ Time out hola ..”“ Time out hello .....”。 但是我想在打印每个“ i == ..”之前看到“超时超时……”。另外,“ End Main”应该是控制台中最后显示的内容。

我该如何解决我的问题?我想了解正在发生的事情,所以我可以很好地学习。

0 个答案:

没有答案