.NET 2.0 中的等效任务

Equivalent Task in .NET 2.0

我知道 .NET 2.0 现在可能真的很老了。
但是我有我想在 .NET 2.0 下编译的代码。不幸的是,源代码使用 .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 中重现相同的行为并提供明确的解释吗?

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(){

}

我的解决方案是使用 BackgroundWorker 并将其包装在辅助程序中 class。
这样您还可以指定其他完成事件。

public delegate void Action();

public class TaskRunner
{
    private readonly object _lock = new object();
    private bool _complete;
    private int _counter;

    public void AddTask(Action action)
    {
        var worker = new BackgroundWorker();
        worker.DoWork += (sender, args) => action();
        worker.RunWorkerCompleted += (sender, args) =>
        {
            try
            {
                Monitor.Enter(_lock);
                if (--_counter == 0)
                {
                    Monitor.Pulse(_lock);
                }
            }
            finally
            {
                Monitor.Exit(_lock);
            }
        };

        try
        {
            Monitor.Enter(_lock);
            if (_complete)
            {
                throw new Exception("task runner is complete");
            }

            _counter++;
            worker.RunWorkerAsync();
        }
        finally
        {
            Monitor.Exit(_lock);
        }
    }

    public void Wait()
    {
        while (!_complete)
        {
            try
            {
                Monitor.Enter(_lock);

                if (_counter == 0)
                {
                    _complete = true;
                    return;
                }

                Monitor.Wait(_lock);
            }
            finally
            {
                Monitor.Exit(_lock);
            }
        }
    }
}

static void Main(string[] args)
{
    var task = new TaskRunner();

    for (var i = 0; i < 10; i++)
    {
        task.AddTask(() => 
        { 
            //Do something
        });
    }

    task.Wait();

    Console.WriteLine("Done");
    Console.ReadLine();
}

希望对您有所帮助。