如何在函数C#.NET中同时运行两个for循环? [英] How to run two for loops at the same time in a function C# .NET?

查看:633
本文介绍了如何在函数C#.NET中同时运行两个for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个函数中有2个for循环,执行不同的工作并一个接一个地运行。如何并行运行它们(两个循环同时执行这些作业)?



I have 2 for loops in a function, doing different jobs and running one after another. How can I run them in parallel(both loops do there jobs at same time) ?

public void func()
{
   for(i=0;i<10;i++)
   {

   }

   for (j=0;j<10;j++)
   {

   }
}





我尝试过:



我在一个函数中有2个for循环,执行不同的工作并一个接一个地运行。如何并行运行它们(两个循环同时执行这些作业)?



What I have tried:

I have 2 for loops in a function, doing different jobs and running one after another. How can I run them in parallel(both loops do there jobs at same time) ?

推荐答案

public void func()
{
    // This code is on thread 1

    Thread ta = new Thread(new ThreadStart(LoopA)); // create thread 2 for LoopA
    Thread tb = new Thread(new ThreadStart(LoopB)); // create thread 3 for LoopB

    ta.Start(); // Run LoopA on thread 2
    tb.Start(); // Run LoopB on thread 3

    // Join makes this thread wait until the thread being joined to has finished

    ta.Join(); // wait for thread 2 to finish
    tb.Join(); // now wait for thread 3 to finish

    // From this point on we know that both loops have completed
}

public void LoopA()
{
    for (int i = 0; i < 1000; i++)
    {
        Console.WriteLine("i = " + i.ToString());
    }
}

public void LoopB()
{
    for (int j = 0; j < 1000; j++)
    {
        Console.WriteLine("j = " + j.ToString());
    }
}


多线程怎么样(例如参见 .NET中的多线程:介绍和建议 [ ^ ])?
What about multiple threads (see, for instance Multi-threading in .NET: Introduction and suggestions[^])?


如何使用基于任务的异步模式

private static async Task MainAsync()

    {
        await MyMethodAsync();
    }

private static async Task MyMethodAsync()
    {
        //start the tasks
        const int count = 10;
        Task<string> loopATask = Task.Run(() => LoopA(count));
        Task<string> loopBTask = Task.Run(() => LoopB(count));
        //await them to complete
        string resultA = await loopATask;
        string resultB = await loopBTask;
        Console.WriteLine(resultA + resultB);
    }


    public static string LoopA(int count)
    {
        for (int i = 0; i < count; i++)
        {
            Console.WriteLine("LoopA " + i);
        }
        return "LoopA has finished ";
    }

    public static string LoopB(int count)
    {
        for (int i = 0; i < count; i++)
        {
            Console.WriteLine("LoopB " + i);
        }
        return "LoopB has finished ";
    }


这篇关于如何在函数C#.NET中同时运行两个for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆