【问题标题】:How to run 2 methods at the same time? [duplicate]如何同时运行 2 个方法? [复制]
【发布时间】:2014-04-22 19:06:26
【问题描述】:

我尝试过使用 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 ());
        }
    }

}

}

我做错了什么?

【问题讨论】:

  • 你想做什么? test2 是否需要由 Update 调用(调用)?他们需要同时启动吗?你考虑过使用线程吗?
  • Task2需要被update调用,不需要同时启动。我试过使用线程,但关于它们的信息很少。
  • 相反,有很多关于启动线程的信息。 google/bing c# 线程、任务、tpl、委托。在旁注中,我觉得这很有趣,因为重复引用了一个被搁置的问题......去图:/

标签: c# coroutine


【解决方案1】:

你需要使用两个线程

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


        }

    }

【讨论】:

  • 收到此错误:当前上下文中不存在名称“任务”
  • 通过将 Task.Factory.StartNew 更改为 System.Threading.Tasks.Task.Factory.StartNew 来修复它。
猜你喜欢
  • 2016-08-23
  • 1970-01-01
  • 2019-06-12
  • 1970-01-01
  • 2021-04-14
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 2014-12-13
相关资源
最近更新 更多