管理多个backgroundWorkers

时间:2014-12-09 23:13:55

标签: c# wpf backgroundworker

我正在开发一个WPF应用程序,即backgroundWorker用文件缩略图填充listBox,并想询问方法是否正常?用户可以随时中断当前后台工作程序。

private readonly List<BackgroundWorker> _backgroundWorkers = new List<BackgroundWorker>();

private void bw_DoWork(object sender, DoWorkEventArgs e)
{
  var bw = (BackgroundWorker)sender;

      // Loop logic
      if (bw.CancellationPending)
      {
          e.Cancel = true;
          return;
      }
      bw.ReportProgress(0, fd);
  }
}

private void RunWorker()
{
    foreach (BackgroundWorker bw in _backgroundWorkers.Where(bw => bw.IsBusy))
    {
        bw.CancelAsync();
    }

    // App logic...

    int i = _backgroundWorkers.Count() + 1;

    var worker = new BackgroundWorker {WorkerReportsProgress = true, WorkerSupportsCancellation = true};
    worker.DoWork += bw_DoWork;
    worker.RunWorkerCompleted += bw_RunWorkerCompleted;
    worker.ProgressChanged += bw_ProgressChanged;
    worker.RunWorkerAsync(i);
    _backgroundWorkers.Add(worker);
}

目的是创建一个新的backgroundWorker并取消现有的忙碌工作者

1 个答案:

答案 0 :(得分:0)

一个后台工作者应该足以获取所有文件缩略图并更新列表框:

public partial class Form1 : Form
{
    private readonly ListBox _listBox;

    public Form1()
    {
        InitializeComponent();

        _listBox = new ListBox();

        var backgroundWorker = new BackgroundWorker
        {
            WorkerReportsProgress = true ,
            WorkerSupportsCancellation = true
        };
        backgroundWorker.DoWork += backgroundWorker_DoWork;
        backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;
        backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;

        backgroundWorker.RunWorkerAsync( new List<object>() );
    }

    void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        var result = new List<object>();

        var backgroundWorker = ( BackgroundWorker ) sender;
        var enumerable = ( IEnumerable<object> ) e.Argument;
        foreach ( var item in enumerable )
        {
            if ( backgroundWorker.CancellationPending )
            {
                e.Cancel = true;
                return;
            }

            // Logic to get file thumbnail

            result.Add( item );

            backgroundWorker.ReportProgress( 0 , item );
        }
        e.Result = result;
    }

    void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        _listBox.Items.Add( e.UserState );
    }

    void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if ( e.Cancelled ) return;
        if ( e.Error != null )
        {
            // Handle exception
            return;
        }
        var listOfThumbnails = e.Result;
    }
}