我有以下设置:
BackgroundWorker backgroundInstancesWorker = new BackgroundWorker();
backgroundInstancesWorker.DoWork += new DoWorkEventHandler(EnumerateInstances);
backgroundInstancesWorker.WorkerReportsProgress = false;
backgroundInstancesWorker.WorkerSupportsCancellation = false;
backgroundInstancesWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundInstancesWorker_RunWorkerCompleted);
// Create temporary tuple to hold the argument information
// X is type IEnumerable<Foo>, Y is type Bar
object arguments = new object[2] { X, Y };
backgroundInstancesWorker.RunWorkerAsync(arguments);
线程工作者函数:
private static void EnumerateInstances(object sender, DoWorkEventArgs e)
{
object[] arguments = e.Argument as object[];
var queryCounterSets = arguments[0] as IEnumerable<Foo>;
var sourceItem = arguments[1] as Bar;
e.Result = sourceItem;
}
终于完成的功能:
private static void backgroundInstancesWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Result != null && e.Result is Bar)
{
// Do stuff
}
}
但是,在 RunWorkerCompleted 函数中,当我尝试访问 e.Result 对象时,它给了我 TargetInvocationException 并说调用线程无权访问该对象,因为另一个线程拥有它。任何人都对为什么这是一个问题有任何见解?我只想在后台线程完成后将 Bar 对象传递给 RunWorkerCompleted 。
谢谢。