如何同时运行2个方法?

时间:2014-04-22 19:06:27

标签: c# coroutine

我尝试过使用system.threading.task.task.factor.startnew,但它仍然会暂停整个事情。

using System;

namespace test
{
class MainClass
{
    public static void test2 ()
    {
        System.Threading.Thread.Sleep(500);
        Console.WriteLine("Test");
    }

    public static void Update ()
    {
        System.Threading.Thread.Sleep(1);
        Console.WriteLine("testt");
    }


    public static void Main ()
    {
        while (true) {
            System.Threading.Tasks.Task.Factory.StartNew (() => test2 ());
            System.Threading.Tasks.Task.Factory.StartNew (() => Update ());
        }
    }

}

}

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您需要使用两个线程

 class MainClass
    {
        public static void Main()
        {
            Task.Factory.StartNew(MainClass.test2);
            Task.Factory.StartNew(MainClass.Update);

            Console.ReadLine();
        }

        public static void test2()
        {
            while (true)
            {
                System.Threading.Thread.Sleep(500);
                Console.WriteLine("Test");

            }
        }

        public static void Update()
        {
            while (true)
            {
                Console.WriteLine("Hello");
                System.Threading.Thread.Sleep(250);
            }


        }

    }
相关问题