.NET 2.0中的等效任务 [英] Equivalent Task in .NET 2.0

查看:80
本文介绍了.NET 2.0中的等效任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道.NET 2.0现在可能已经很旧了.
但是我有要在.NET 2.0下编译的代码.不幸的是,源代码使用.NET 4.0 System.Threading.Tasks

I know .NET 2.0 it's probably really old now.
But I have the code that I want to compile under .NET 2.0. Unfortunately, the source uses .NET 4.0 System.Threading.Tasks

代码在这里:

int count = GetCount();

Task[] tasks = new Task[count];

for (int p = 0; p < count; p++)
{
     int current = p;
     tasks[p] = Task.Run(() =>
     {
         // Do something here
     });
}
Task.WaitAll(tasks);

我不是线程专家 有人可以在.NET 2.0中重现相同的行为以及清楚的解释?

I'm not expert in threading can someone reproduce same behavior in .NET 2.0 along with clear explanation?

推荐答案

public void Start(){
    int count = GetCount();

    //create an array of Thread objects for later access
    Thread[] threads = new Thread[count];

    for (int p = 0; p < count; p++)
    {
         //Create a new Thread
         threads[p] = new Thread(DoSomething);  //.Net 2.0 doesn't have support for lambda expressions, so use a method instead
         //Start the Thread
         threads[p].Start();
    }

    //Wait for all threads to finish execution
    foreach(var t in threads){
        t.Join(); //Thread.Join blocks until the Thread finished executing
    }
}

//this method will be executed by the threads
public void DoSomething(){

}

这篇关于.NET 2.0中的等效任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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