如何使用委托BackgroundWorker
本文关键字:BackgroundWorker 何使用 | 更新日期: 2023-09-27 18:07:06
我试着用Kinect写一个WPF应用程序,所以我写了下面的代码:
static BackgroundWorker _bw = new BackgroundWorker();
_bw.DoWork += bw_DoWork;
_bw.RunWorkerAsync();
dispatcherTimerGame = new System.Windows.Threading.DispatcherTimer();
dispatcherTimerGame.Tick += new EventHandler(dispatcher_VerificaCarte);
dispatcherTimerGame.Interval = new TimeSpan(0, 0, 1);
dispatcherTimerGame.Start();
void bw_DoWork(object sender, DoWorkEventArgs e)
{
try
{
this.sensorChooser = new KinectSensorChooser();
this.sensorChooser.KinectChanged += SensorChooserOnKinectChanged;
this.sensorChooserUi.KinectSensorChooser = this.sensorChooser;
this.sensorChooser.Start();
this.sensor = this.sensorChooser.Kinect;
if (this.sensor != null)
{
DateTime dat1 = DateTime.Now;
string date = DateTime.Now.ToString("dd-MMM-yy HH-mm");
acquisizioneVideo = new Acquisizione("Video" + date + ".avi");
this.sensor.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30);
acquisizioneAudio = new AcquisizioneWaveAudio(180, this.sensor, "Audio" + date + ".wav"); acquisizioneAudio.recordAudio();
acquisizioneVideo.recordVideo();
this.sensor.ColorFrameReady += acquisizioneVideo.ColorImageReady;
}
}
catch (Exception exc)
{
log.Error(exc);
}
}
所以当我尝试执行这段代码时this.sensorChooserUi.KinectSensorChooser = this.sensorChooser;
,我有这个错误:
[System.InvalidOperationException] = {"The calling thread cannot access this object because a different thread owns it."}"
我该如何修复它?
你需要像这样在主线程上调用这些调用
this.Dispatcher.Invoke(() =>
this.sensorChooser = new KinectSensorChooser();
this.sensorChooser.KinectChanged += SensorChooserOnKinectChanged;
this.sensorChooserUi.KinectSensorChooser = this.sensorChooser;
this.sensorChooser.Start();
this.sensor = this.sensorChooser.Kinect;
});
你可能需要将任何这样的代码包装在分派器调用中。
通常对这类元素的任何调用都具有线程亲缘性,因此它们要求使用创建方法的同一线程调用方法。对你来说是这样的。sensorChooserUi是在另一个线程中创建的,然后是this.sensorChooser.
你可能不得不选择性地选择可以异步执行的代码段。通常不是每个代码都是异步的。因此,一定要确定代码中昂贵的部分,并在允许的情况下异步执行。通常IO调用、网络调用都是async的好选择。另一种方法是找到易受攻击的代码部分,并将其封装在dispatcher调用中。