我尝试使用WPF MediaKit (MediaDetector class)库创建Video To Gif转换器以逐帧提取视频。我想使用async / await异步运行StartButton_OnClick
方法。
我使用以下代码:
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()
方法:
public override Task StartConverting()
{
return Task.Run(() =>
{
Encoder.Start(GifPath);
Encoder.SetDelay(Ival);
Encoder.SetRepeat(0);
for (double i = From; i < To; i += Ival)
{
var frame = GetFrame(TimeSpan.FromMilliseconds(i));
frame = ResizeImage(frame);
AddFrame(frame);
}
Encoder.Finish();
});
}
GetFrame(TimeSpan ts)
方法:
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时,我收到一条带有消息&#34的System.InvalidOperationException;调用线程无法访问此对象,因为另一个线程拥有它&#34;
在这一行GetImage()
方法(look this)
if (string.IsNullOrEmpty(m_filename))
我是多线程编程的初学者。我怎么能解决这个问题?
P.S。抱歉我的英语不好: - )
答案 0 :(得分: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
也是可能的,虽然我不推荐它。