将KeyValuePair列表从backgroundWorker1传递到backgroundWorker2

本文关键字:backgroundWorker2 backgroundWorker1 KeyValuePair 列表 | 更新日期: 2023-09-27 18:18:14

我有一个小问题,我正在使用

var filelist = new List<KeyValuePair<string, string>>();
 filelist.Add(new KeyValuePair<string, string>(a, b));
 filelist.Add(new KeyValuePair<string, string>(c,d));

在backgroundWorker1中,做它需要做的事情,当backgroundWorker1完成后,列表应该以某种方式传递给backgroundWorker2。

我甚至不知道从哪里开始这样做,所以任何帮助都是非常感谢的。

将KeyValuePair列表从backgroundWorker1传递到backgroundWorker2

确保该列表对工人和事件变量都是可见的(例如,它可以是AutoresetEvent)。然后,当backgroundworker1中列表上的工作完成时,通知第二个工人读取它:

// prepare the list
event.Set();

backgroundworker2中,您应该在事件的某个点等待:

event.WaitOne();
// use the list

你可以简单地在你用来处理第一个BackgroundWorker的RunWorkerCompleted事件的委托中启动第二个BackgroundWorker。

只需将bw# 2的RunWorkerAsync调用中的参数设置为bw# 1的返回值。

听起来bw# 2在bw# 1完成之前没有任何事情要做,所以实现共享状态或引发事件或实现观察者类型模式没有意义。

让第一个的RunWorkerCompleted用一个参数开始第二个。下面是一个示例,用于了解如何将参数从第一个发送到第二个。

public Form1()
{
    InitializeComponent();
    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
    backgroundWorker2.DoWork += backgroundWorker2_DoWork;
    backgroundWorker2.RunWorkerCompleted += backgroundWorker2_RunWorkerCompleted;
    backgroundWorker1.RunWorkerAsync();
}

void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    e.Result = "a";
}
void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    string s = (string)e.Result;
    backgroundWorker2.RunWorkerAsync(s);
}
void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
    e.Result = (string)e.Argument;
}
void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    Text = (string)e.Result;
}
相关文章:
  • 没有找到相关文章