簡體   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