繁体   English   中英

如何使用委托BackgroundWorker?

[英]How to use delegate BackgroundWorker?

我尝试使用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;
});

您可能必须将所有此类代码包装在调度程序调用中。

通常,对此类元素的任何调用都具有线程相似性,因此它们要求使用与其创建时相同的线程来调用方法。 在您的情况下,this.sensorChooserUi是与this.sensorChooser不同的线程创建的。

更新资料

您可能必须有选择地选择可以异步执行的代码段。 通常,并非每个代码都意味着异步。 因此请确定您代码的昂贵部分,并在允许的情况下使其异步。 通常是IO调用,网络调用是异步的理想选择。 另一种方法是查找代码中易受攻击的部分,并将其包装在分派器调用中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM