2014-01-11 66 views
2

我正在嘗試使用WPF MediaKit (MediaDetector class)庫創建視頻轉換爲Gif轉換器以逐幀提取視頻幀。我想用async/await異步運行StartButton_OnClick方法。在C中異步調用方法#

我用下面的代碼:

private async void StartButton_OnClick(object sender, RoutedEventArgs e) 
{ 
    if (_openFile != null && 
     !String.IsNullOrEmpty(SaveToBox.Text)) 
    { 
     await new LocalVideoConverter(_openFile.FileName, _from*1000, _to*1000, 
      SaveToBox.Text, InterpolationMode.Low, new System.Drawing.Size(320, 240)) 
      .StartConverting(); 
    } 
    else 
     MessageBox.Show("Choose video file and enter path for Gif"); 
} 

StartConverting()方法:

方法:

protected override Image GetFrame(TimeSpan ts) 
{ 
    var bitmapSource = _mediaDetector.GetImage(ts); 
    using (var outStream = new MemoryStream()) 
    { 
     BitmapEncoder enc = new BmpBitmapEncoder(); 
     enc.Frames.Add(BitmapFrame.Create(bitmapSource)); 
     enc.Save(outStream); 
     return new Bitmap(outStream); 
    } 
} 

而且MediaDetector類有public unsafe BitmapSource GetImage(TimeSpan position)方法。


當我點擊StartButton,我得到消息一個System.InvalidOperationException「因爲不同的線程擁有它調用線程不能訪問該對象」 在此行中GetImage()方法(look this

if (string.IsNullOrEmpty(m_filename)) 

我是多線程編程的初學者。我該如何解決這個問題?

P.S.對不起,我的英文不好:-)

+1

很確定該異常只是之前的一行,其中[Dispatcher.VerifyAccess](http://msdn.microsoft.com/zh-cn/library/system.windows.threading.dispatcher.verifyaccess.aspx)是調用。它檢查當前線程是否允許方法調用,這顯然不是這種情況。您可以通過同步執行Dispatcher線程中的GetImage方法來解決此限制,即將它傳遞給[Dispatcher.Invoke](http://msdn.microsoft.com/zh-cn/library/system.windows.threading。調用.dispatcher.invoke.aspx)。 – Clemens

回答

2

您可能會遇到async/await使用BeginInvoke。由於它是WPF,我想你可以寫

private void StartButton_OnClick(object sender, RoutedEventArgs e) { 
    if (_openFile != null && !String.IsNullOrEmpty(SaveToBox.Text)) { 
     this.Dispatcher.BeginInvoke(new Action(delegate() { 
      LocalVideoConverter lvc = new LocalVideoConverter(_openFile.FileName, _from*1000, _to*1000, 
      SaveToBox.Text, InterpolationMode.Low, new System.Drawing.Size(320, 240)); 
      lvc.StartConverting(); 
     })); 
    } else 
     MessageBox.Show("Choose video file and enter path for Gif"); 
} 

BackgroundWorker也許是可能的,但我不會推薦它。