0

これを機能させるためにさまざまな方法を試しましたが、それはマルチスレッド用に async/await を接続する適切な方法ではないと確信しています。これが私がこれまでに持っているものです。非同期にしてみたのがディレクトリウォーカーです。async または await キーワードが表示されないことはわかっていますが、それは私が失敗したためですが、それが私がやろうとしていることです。現在はコンソール アプリケーションで実行されていますが、機能する POC を取得したら、後で抽象化してリファクタリングします。任意のガイダンスをいただければ幸いです。

    static void RunProgram(CancellationToken ct)
    {
        try
        {
            foreach (var dir in _directoriesToProcess)
            {
                var newTask = CreateNewTask(dir, ct);
                _tasks.Add(newTask);
            }

            while (_tasks.Count > 0)
            {
                lock (_collectionLock)
                {
                    var t = _tasks.Where(x => x.IsCompleted == true).ToList();
                    if (t != null)
                        foreach (var task in t)
                        {
                            _tasks.Remove(task);
                        }
                }
            }

            OutputFiles();
            StopAndCleanup();
        }
        catch (Exception ex)
        {
            Log(LogColor.Red, "Error: " + ex.Message, false);
            _cts.Cancel();
        }
    }


    static Task CreateNewTask(string Path, CancellationToken ct)
    {
        return Task.Factory.StartNew(() => GetDirectoryFiles(Path, ct), ct);
    }

    static void GetDirectoryFiles(string Path, CancellationToken ct)
    {
        if (!ct.IsCancellationRequested)
        {
            List<string> subDirs = new List<string>();
            int currentFileCount = 0;
            try
            {
                currentFileCount = Directory.GetFiles(Path, _fileExtension).Count();
                subDirs = Directory.GetDirectories(Path).ToList();

                lock (_objLock)
                {
                    _overallFileCount += currentFileCount;
                    Log(LogColor.White, "- Current path: " + Path);
                    Log(LogColor.Yellow, "--  Sub directory count: " + subDirs.Count);
                    Log(LogColor.Yellow, "--  File extension: " + _fileExtension);
                    Log(LogColor.Yellow, "--  Current count: " + currentFileCount);
                    Log(LogColor.Red, "--  Running total: " + _overallFileCount);
                    _csvBuilder.Add(string.Format("{0},{1},{2},{3}", Path, subDirs.Count, _fileExtension, currentFileCount));
                    Console.Clear();
                    Log(LogColor.White, "Running file count: " + _overallFileCount, false, true);
                }

                foreach (var dir in subDirs)
                {
                    lock (_collectionLock)
                    {
                        var newTask = CreateNewTask(dir, ct);
                        _tasks.Add(newTask);
                    }
                }
            }
            catch (Exception ex)
            {
                Log(LogColor.Red, "Error: " + ex.Message, false);
                _cts.Cancel();
            }
        }
    }
4

2 に答える 2

1

あなたがやろうとしていることには何の問題もないと思います。たとえば、異なるスレッドで一度にあまりにも多くのディレクトリを読み取るなど、制御されていない並行性に注意してください。コンテキストの切り替えにより、処理が遅くなる可能性があります。

メソッドの副作用として何かを行う代わりに、収集した値を返すようにしてください。例えば

static async Task<IEnumerable<DirectoryStat>> GetDirectoryFiles(string path, string fileExtension, CancellationToken ct)
{
    var thisDirectory = await Task.Run(() => /* Get directory file count and return a DirectoryStat object */);
    var subDirectoriesResults = await Task.WhenAll(Directory.GetDirectories(path).Select(dir => GetDirectoryFiles(dir, fileExtension, ct)));

    return (new[] { thisDirectory }).Concat(subDirectoryResults);
} 

その後、後でそれらを繰り返して、必要なデータを取得できますDirectoryStat(そして、ファイルカウントなどを合計します_overallFileCount

注:未テスト:)

于 2016-01-10T00:07:58.067 に答える