1

PTL の調査を始めたばかりで、設計に関する質問があります。

私のシナリオ: それぞれが画像を参照する URL のリストがあります。各画像を並行してダウンロードしたい。少なくとも 1 つのイメージがダウンロードされるとすぐに、ダウンロードしたイメージで何かを行うメソッドを実行したいと考えています。そのメソッドは並列化すべきではありません。シリアル化する必要があります。

以下はうまくいくと思いますが、これが正しい方法かどうかはわかりません。画像を収集するためのクラスと、収集した画像で「何か」を行うためのクラスが別々にあるため、タスクの配列を渡すことになります。これは、画像の取得方法の内部動作を公開するため、間違っているようです。しかし、私はそれを回避する方法を知りません。実際には、これらの方法の両方にさらに多くの機能がありますが、これは重要ではありません。画像の取得と処理の両方を行う 1 つの大きなメソッドにまとめてはいけません。

//From the Director class
Task<Image>[] downloadTasks = collector.RetrieveImages(listOfURLs);

for (int i = 0; i < listOfURLs.Count; i++)
{
    //Wait for any of the remaining downloads to complete
    int completedIndex = Task<Image>.WaitAny(downloadTasks);
    Image completedImage = downloadTasks[completedIndex].Result;

    //Now do something with the image (this "something" must happen serially)
    //Uses the "Formatter" class to accomplish this let's say
}

///////////////////////////////////////////////////

//From the Collector class
public Task<Image>[] RetrieveImages(List<string> urls)
{
    Task<Image>[] tasks = new Task<Image>[urls.Count];

    int index = 0;
    foreach (string url in urls)
    {
        string lambdaVar = url;  //Required... Bleh
        tasks[index] = Task<Image>.Factory.StartNew(() =>
            {
                using (WebClient client = new WebClient())
                {
                    //TODO: Replace with live image locations
                    string fileName = String.Format("{0}.png", i);
                    client.DownloadFile(lambdaVar, Path.Combine(Application.StartupPath, fileName));
                }

                return Image.FromFile(Path.Combine(Application.StartupPath, fileName));
            },
            TaskCreationOptions.LongRunning | TaskCreationOptions.AttachedToParent);

        index++;
    }

    return tasks;
}
4

4 に答える 4

9

通常、WaitAny は、他のタスクの結果を気にしない場合に、1 つのタスクを待機するために使用します。たとえば、たまたま返された最初の画像を気にした場合などです。

代わりにこれはどうでしょう。

これにより、2 つのタスクが作成されます。1 つはイメージをロードし、ブロッキング コレクションに追加するタスクです。2 番目のタスクはコレクションを待機し、キューに追加されたイメージを処理します。すべての画像がロードされると、最初のタスクがキューを閉じて、2 番目のタスクがシャットダウンできるようにします。

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Net;
using System.Threading.Tasks;

namespace ClassLibrary1
{
    public class Class1
    {
        readonly string _path = Directory.GetCurrentDirectory();

        public void Demo()
        {
            IList<string> listOfUrls = new List<string>();
            listOfUrls.Add("http://i3.codeplex.com/Images/v16821/editicon.gif");
            listOfUrls.Add("http://i3.codeplex.com/Images/v16821/favorite-star-on.gif");
            listOfUrls.Add("http://i3.codeplex.com/Images/v16821/arrow_dsc_green.gif");
            listOfUrls.Add("http://i3.codeplex.com/Images/v16821/editicon.gif");
            listOfUrls.Add("http://i3.codeplex.com/Images/v16821/favorite-star-on.gif");
            listOfUrls.Add("http://i3.codeplex.com/Images/v16821/arrow_dsc_green.gif");
            listOfUrls.Add("http://i3.codeplex.com/Images/v16821/editicon.gif");
            listOfUrls.Add("http://i3.codeplex.com/Images/v16821/favorite-star-on.gif");
            listOfUrls.Add("http://i3.codeplex.com/Images/v16821/arrow_dsc_green.gif");

            BlockingCollection<Image> images = new BlockingCollection<Image>();

            Parallel.Invoke(
                () =>                   // Task 1: load the images
                {
                    Parallel.For(0, listOfUrls.Count, (i) =>
                        {
                            Image img = RetrieveImages(listOfUrls[i], i);
                            img.Tag = i;
                            images.Add(img);    // Add each image to the queue
                        });
                    images.CompleteAdding();    // Done with images.
                },
                () =>                   // Task 2: Process images serially
                {
                    foreach (var img in images.GetConsumingEnumerable())
                    {
                        string newPath = Path.Combine(_path, String.Format("{0}_rot.png", img.Tag));
                        Console.WriteLine("Rotating image {0}", img.Tag);
                        img.RotateFlip(RotateFlipType.RotateNoneFlipXY);

                        img.Save(newPath);
                    }
                });
        }

        public Image RetrieveImages(string url, int i)
        {
            using (WebClient client = new WebClient())
            {
                string fileName = Path.Combine(_path, String.Format("{0}.png", i));
                Console.WriteLine("Downloading {0}...", url);
                client.DownloadFile(url, Path.Combine(_path, fileName));
                Console.WriteLine("Saving {0} as {1}.", url, fileName);
                return Image.FromFile(Path.Combine(_path, fileName));
            }
        } 
    }
}

警告: コードにはエラー チェックやキャンセルがありません。遅くなりましたが、何かする必要がありますか?:)

これは、パイプライン パターンの例です。画像の取得は非常に遅く、ブロッキング コレクション内でのロックのコストは、画像のダウンロードに費やされる時間に比べて比較的まれにしか発生しないため、問題を引き起こさないと想定しています。

私たちの本... 並列プログラミングのこのパターンやその他のパタ​​ーンについては、 http://parallelpatterns.codeplex.com/で詳しく読むことができます 。

于 2010-06-26T05:29:50.337 に答える
2

TPL には、別のタスクが終了したときに 1 つのタスクを実行するための ContinueWith 関数が既に用意されています。タスク チェーンは、TPL で非同期操作に使用される主なパターンの 1 つです。

次のメソッドは、一連の画像をダウンロードし、各ファイルの名前を変更して続行します

static void DownloadInParallel(string[] urls)
{
   var tempFolder = Path.GetTempPath();

   var downloads = from url in urls
                   select Task.Factory.StartNew<string>(() =>{
                       using (var client = new WebClient())
                       {
                           var uri = new Uri(url);
                           string file = Path.Combine(tempFolder,uri.Segments.Last());
                           client.DownloadFile(uri, file);
                           return file;
                       }
                   },TaskCreationOptions.LongRunning|TaskCreationOptions.AttachedToParent)
                  .ContinueWith(t=>{
                       var filePath = t.Result;
                       File.Move(filePath, filePath + ".test");
                  },TaskContinuationOptions.ExecuteSynchronously);

    var results = downloads.ToArray();
    Task.WaitAll(results);
}

ParallelExtensionsExtras サンプルのWebClient Async Tasksも確認する必要があります。DownloadXXXTask 拡張メソッドは、タスクの作成とファイルの非同期ダウンロードの両方を処理します。

次のメソッドは、DownloadDataTask 拡張機能を使用して画像のデータを取得し、ディスクに保存する前に回転させます。

static void DownloadInParallel2(string[] urls)
{
    var tempFolder = Path.GetTempPath();

    var downloads = from url in urls
         let uri=new Uri(url)
         let filePath=Path.Combine(tempFolder,uri.Segments.Last())
         select new WebClient().DownloadDataTask(uri)                                                        
         .ContinueWith(t=>{
            var img = Image.FromStream(new MemoryStream(t.Result));
            img.RotateFlip(RotateFlipType.RotateNoneFlipY);
            img.Save(filePath);
         },TaskContinuationOptions.ExecuteSynchronously);

    var results = downloads.ToArray();
    Task.WaitAll(results);
}
于 2010-06-09T10:01:27.623 に答える
0

これを行う最良の方法は、おそらくObserverパターンを実装することです。RetreiveImages関数にIObservableを実装させ、「完了したイメージアクション」をIObserverオブジェクトのOnNextメソッドに入れて、サブスクライブしRetreiveImagesます。

私はまだこれを試していませんが(タスクライブラリでもっと遊ぶ必要があります)、これが「正しい」方法だと思います。

于 2010-06-09T07:34:56.103 に答える
0

//すべての画像をダウンロード

private async void GetAllImages ()
{
    var downloadTasks = listOfURLs.Where(url =>   !string.IsNullOrEmpty(url)).Select(async url =>
            {
                var ret = await RetrieveImage(url);
                return ret;
        }).ToArray();

        var counts = await Task.WhenAll(downloadTasks);
}

//From the Collector class
public async Task<Image> RetrieveImage(string url)
{
    var lambdaVar = url;  //Required... Bleh
    using (WebClient client = new WebClient())
    {
        //TODO: Replace with live image locations
        var fileName = String.Format("{0}.png", i);
        await client.DownloadFile(lambdaVar, Path.Combine(Application.StartupPath, fileName));
    }
    return Image.FromFile(Path.Combine(Application.StartupPath, fileName));
}  
于 2013-05-13T18:22:06.440 に答える