Example #1
0
    public bool Run(IList <string> folders, IList <string> files)
    {
        var cancellation = new CancellationTokenSource();

        _cancel = cancellation.Token;

        using (var task = Task.Factory.StartNew(() =>
        {
            // do folders (parallel)
            if (folders.Count > 0)
            {
                //! do not use aggregation, see file remarks
                Parallel.ForEach(folders, new ParallelOptions()
                {
                    CancellationToken = _cancel
                }, folder =>
                {
                    Check();
                    _Result.Add(new FolderItem()
                    {
                        Name = Path.GetFileName(folder), Size = CalculateFolderSize(folder)
                    });
                    _progress.SetProgressValue(_Result.Count, folders.Count);
                });
            }

            Check();

            // do files (serial)
            if (files.Count > 0)
            {
                _progress.Activity = "Computing file sizes";
                foreach (var file in files)
                {
                    try
                    {
                        var info = new FileInfo(file);
                        _Result.Add(new FolderItem()
                        {
                            Name = info.Name, Size = info.Length
                        });
                    }
                    catch (Exception ex)
                    {
                        _Errors.Add(ex);
                    }
                }
            }

            Check();

            // done
            _progress.Complete();
        }, _cancel))
        {
            if (!task.Wait(750))
            {
                _progress.Title     = "Computing sizes";
                _progress.Canceled += delegate
                {
                    cancellation.Cancel(true);
                };
                _progress.CanCancel = true;
                _progress.Show();
            }

            try
            {
                task.Wait();
            }
            catch (AggregateException)
            { }

            return(task.Status == TaskStatus.RanToCompletion);
        }
    }