2014-06-06 48 views
0

我嘗試寫與Kinect的WPF應用程序,所以我必須寫這樣的代碼:當我嘗試執行該代碼 this.sensorChooserUi.KinectSensorChooser = this.sensorChooser;, 我有這樣的錯誤如何使用委託BackgroundWorker?

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); 
    } 
} 

所以:

[System.InvalidOperationException] = {"The calling thread cannot access this object because a different thread owns it."}" 

我該如何解決它?

回答

0

你需要在主線程中調用此類呼叫這樣

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調用,網絡調用是異步的好選擇。其他方法是找到代碼中易受攻擊的部分並將其包裝在調度程序調用中。

+0

好的,謝謝,但我已經使用BackgroundWorker,因爲我想在Kinect初始化時執行其他代碼。如果我在main方法中編寫此代碼,我沒有AsyncTask – bircastri

+0

,如果可能的話,您可能會執行其他代碼異步。 – pushpraj