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

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

问题描述

我正在构建一个 WP8 应用程序,我需要执行大约 30 个网络请求.这些请求不相互依赖,因此可以并行处理.

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.

我的代码看起来像这样(简化/伪代码):

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

当我查看 Fiddler 时,请求都是按顺序执行的;执行和处理所有这些需要几秒钟的时间.但是,我不希望代码等到 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() 或类似的东西来做到这一点,但显然 Parallel 库在 Windows 中不可用电话 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()?new 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();

此代码获取 uris 的集合,并为每个 (Select(...)) 启动 HTTP 下载.然后异步等待它们全部完成 (WhenAll).然后在第二行代码中处理所有数据.

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天全站免登陆