Equivalent Task in .NET 2.0 [duplicate]

落爺英雄遲暮 提交于 2019-12-07 21:54:40

问题


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

Here the code:

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

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


回答1:


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

}



回答2:


My solution would be to use a BackgroundWorker and wrap it in a helper class.
This way you could also specify additional completion events.

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

Hope it helps.



来源:https://stackoverflow.com/questions/34087518/equivalent-task-in-net-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!