【问题标题】:how to execute a third method after first and second method in c#如何在c#中的第一种和第二种方法之后执行第三种方法
【发布时间】:2015-10-24 19:08:37
【问题描述】:

我有两个使用Task 类在线程中运行的方法。我有第三种方法在主线程中执行。我希望在第一种和第二种方法之后执行第三种方法。如何在以下代码中执行此操作。在Firstmethod() 和Secondmethod() 之后只有Thirdmethod() 被执行

static void Main(string[] args)
{
    Task.Factory.StartNew(() => { Firstmethod();
    });
    Task.Factory.StartNew(() => { Secondmethod();
    });

        Thirdmethod();
    Console.ReadLine();
}

static void Firstmethod()
{
    for (int i = 0; i < 10; i++)
    {
        Console.WriteLine(i);
    }
}
static void Secondmethod()
{
    for (int i = 10; i < 20; i++)
    {
        Console.WriteLine(i);
    }
}
static void Thirdmethod()
{
    for (int i = 20; i < 30; i++)
    {
        Console.WriteLine(i);
    }
}

【问题讨论】:

  • 您必须等待第一个和第二个任务。最好使用 Task.WaitAll
  • 搜索 AutoResetEvent/ManualResetEvent
  • 我使用的是 .net 4.0 而不是 4.5 任何机构都可以发布代码来执行此操作

标签: c# .net multithreading .net-4.0 task-parallel-library


【解决方案1】:

使用Task.WaitAll。它在 .NET 4.0 中可用。

static void Main(string[] args)
{
    Task t1 = Task.Factory.StartNew(() => {
        Firstmethod();
    });
    Task t2 = Task.Factory.StartNew(() => {
        Secondmethod();
    });

    Task.WaitAll(t1, t2);
    Thirdmethod();
    Console.ReadLine();
}

【讨论】:

    【解决方案2】:

    虽然 Jakub 的回答是正确的,但它可能更有效。使用 Task.WaitAll 会阻塞线程,而其他 2 个线程执行第一个和第二个操作。

    您可以使用它来执行其中一种方法,而不是阻塞该线程,然后再阻塞另一种方法。这只会使用 2 个线程而不是 3 个,甚至可能根本不会阻塞:

    static void Main()
    {
        Task task = Task.Factory.StartNew(() => FirstMethod()); // use another thread
        SecondMethod(); // use the current thread
        task.Wait(); // make sure the first method completed
        Thirdmethod();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 2020-12-17
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 2022-01-21
      相关资源
      最近更新 更多