c#创建不同数量的线程

时间:2011-11-04 19:10:33

标签: c# multithreading

我有一种方法可以根据用户的输入创建不同数量的请求。对于每个输入,我必须创建一个对象的实例并在新线程中从该对象运行方法。 这意味着我永远不知道,我需要多少线程。 之后我将不得不访问我之前创建的每个实例的数据。

所以问题是:如何根据用户的输入创建不同数量的请求(以及每个请求一个线程)?

一个例子:

userInput = [start, end, start2, end2, start3, end3]

//for each pair Start-end create instance with unique name or make it other way accessible
Request req1 = new Request('start', 'end')
Request req2 = new Request('start2', 'end2')
Request req3 = new Request('start3', 'end3')

//create thread for each instance
Thread t1 = new Thread(new ThreadStart(req1.GetResponse));
t1.Start();
Thread t2 = new Thread(new ThreadStart(req2.GetResponse));
t2.Start();
Thread t3 = new Thread(new ThreadStart(req3.GetResponse));
t3.Start();

//get data from each instance
string a = req1.result
string b = req2.result
string c = req3.result

3 个答案:

答案 0 :(得分:1)

如果您使用的是.NET 3.5或更低版本,则可以使用ThreadPool.QueueUserWorkItem方法,如果您使用的是.NET 4.0,请使用TPL

答案 1 :(得分:1)

在.NET 4中,这可以通过Task<T>完成。而不是制作一个帖子,你可以这样写:

Request req1 = new Request("start", "end");
Task<string> task1 = req1.GetResponseAsync(); // Make GetResponse return Task<string>

// Later, when you need the results:
string a = task1.Result; // This will block until it's completed.

然后您可以编写GetRepsonseAsync方法,例如:

public Task<string> GetRepsonseAsync()
{
     return Task.Factory.StartNew( () =>
     {
          return this.GetResponse(); // calls the synchronous version
     });
}

答案 2 :(得分:1)

您不应该按Request创建新主题。而是利用ThreadPool,使用TPL,PLINQ或ThreadPool.QueueUserWorkItem

如何使用PLINQ执行此操作的示例:

public static class Extensions
{
    public static IEnumerable<Tuple<string, string>> Pair(this string[] source)
    {
        for (int i = 0; i < source.Length; i += 2)
        {
            yield return Tuple.Create(source[i], source[i + 1]);
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        var userinput = "start, end, start2, end2, start3, end3, start4, end4";

        var responses = userinput 
                        .Replace(" ", string.Empty)
                        .Split(',')
                        .Pair()
                        .AsParallel()
                        .Select(x => new Request(x.Item1, x.Item2).GetResponse());

        foreach (var r in responses)
        {
            // do something with the response
        }

        Console.ReadKey();
    }
}