如何运行在Windows Phone并行任务? [英] How to run parallel tasks on Windows Phone?

查看:96
本文介绍了如何运行在Windows Phone并行任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立一个WP8应用程序,我需要执行大约30 Web请求。这些要求不依赖于对方,使他们能够进行并行化。

I'm building a WP8 app and I need to perform around 30 web requests. These requests don't depend on each other so they could be parallelized.

我的code看起来像这样(简体/伪code):

My code looks like this (simplified/pseudocode):

foreach (Uri uri in uris)
{
    var rawData = await Task.Run(() => httpClient.GetStringAsync(uri).ConfigureAwait(false));

    var processedData = dataProcessor.Process(rawData);
    processedDataCollection.Add(processedData);
}

当我看到提琴手,这些请求都进行sequantial;它需要几秒钟来执行和处理他们。不过,我不希望code等到1请求被移动到下一个之前完成,我想在同一时间执行多个请求。

When I look at Fiddler, the requests are all performed sequantial; it takes a few seconds to perform and process all of them. However, I don't want the code to wait until 1 request is finished before moving to the next one, I want to perform multiple requests at the same time.

通常我会使用 Parallel.Invoke() Parallel.ForEach()或类似的东西做这一点,但显然并行库不可用在Windows Phone 8的。

Normally I would use Parallel.Invoke() or Parallel.ForEach() or something like that to do this, but apparently the Parallel library is not available in Windows Phone 8.

那么,什么是完成这一任务的最佳方式? Task.Factory.StartNew()新的Thread()

So what's the best way to accomplish this? Task.Factory.StartNew()? new Thread()?

推荐答案

有没有必要运行在单独的线程每个请求。你可以很容易地做到这一点:

There's no need to run each request on a separate thread. You can just as easily do this:

var raw = await Task.WhenAll(uris.Select(uri => httpClient.GetStringAsync(uri)));
var processed = raw.Select(data => dataProcessor.Process(data)).ToArray();

这code采用的URI 的集合,开始一个HTTP下载的每一个(选择(...))。然后异步等待他们全部完成( WhenAll )。然后,所有数据在code的第二行处理。

This code takes the collection of uris and starts an HTTP download for each one (Select(...)). Then it asynchronously waits for them all to complete (WhenAll). All the data is then processed in the second line of code.

但是,很可能在Windows Phone运行时会限制你可以在同一台服务器的请求的最大数量。

However, it's likely that the Windows Phone runtime will limit the maximum number of requests you can have to the same server.

这篇关于如何运行在Windows Phone并行任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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