How to launch 10 tasks in parallel



  • Got a list of tasks. At this point, I'm launching them without flow. But it's all going very slow, and I'm thinking about using flows. But it's not quite clear what design is better and easier to use here? ThreadPoolTask etc.

    var data1 = parse("www.ya.ru");
    var data2 = parse("www.google.ru");
    var data3 = parse("www.yahoo.ru");
    ....
    


  • In addition to the answers already available, perhaps in this task, you should consider Parallel LINQ:

    var uris = new[] { "www.ya.ru", "www.google.ru", "www.yahoo.ru" };
    var data = uris.AsParallel().Select(parse).ToList();
    

    About Task'Oh, I like that syntaxy.

    var uris = new[] { "www.ya.ru", "www.google.ru", "www.yahoo.ru" };
    var tasks = uris.Select(uri => Task.Run(() => parse(uri));
    var results = await Task.WhenAll(tasks);
    

    To avoid free flows without cause, I would recommend a method. parse Make asynchronous, then the code becomes more effective:

    async Task<Data> parse(string uri)
    {
        string content;
        using (var cl = new WebClient())
             content = await cl.DownloadStringTaskAsync(uri);
        // собственно разбор есть CPU-bound -- выгружаем в пул потоков
        return await Task.Run(() => ParseContent(content));
    }
    

    var uris = new[] { "www.ya.ru", "www.google.ru", "www.yahoo.ru" };
    var tasks = uris.Select(parse);
    var results = await Task.WhenAll(tasks);

    Perhaps better use is made of lighter and modern. HttpClient:

    using (var cl = new HttpClient())
    content = await cl.GetStringAsync(uri);




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2