我想使用Mutli線程保存所有UserControl
作爲圖像在同一時間想要顯示動畫視圖屏幕上,但有一個錯誤:使用多線程保存UserControls作爲圖像的錯誤是:調用線程不能訪問這個對象,因爲不同的線程擁有它
The calling thread cannot access this object because a different thread owns it.
這是我的代碼:
private void OnScreenShotAllCommandExecuted(object parameter)
{
string filePath = @"D:\ScreenShot\";
IList<UserControl> userControls = LayoutRoot.Children.OfType<UserControl>().ToList();
List<Thread> tasks = new List<Thread>();
AnimationView animationView = new AnimationView();
animationView.Show();
foreach (UserControl userControl in userControls)
{
string viewName = userControl.Name;
string fileName = userControl.Name + ".png";
if (viewName != null)
{
Thread thread = new Thread(() =>
{
Thread.Sleep(1000);
SaveView(userControl, fileName, filePath);
ThreadHasFinished();
});
tasks.Add(thread);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
}
}
private void ThreadHasFinished()
{
Interlocked.Increment(ref finishedControls);
Dispatcher.BeginInvoke((Action)(() =>
{
animationView.Close();
}));
}
public static void SaveView(UserControl userControl, string fileName, string destFolder)
{
Rect bounds = VisualTreeHelper.GetDescendantBounds(userControl);
int width = (int)view.RenderSize.Width;
int height = (int)view.RenderSize.Height;
RenderTargetBitmap rtb = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
DrawingVisual dv = new DrawingVisual();
using (DrawingContext ctx = dv.RenderOpen())
{
VisualBrush vb = new VisualBrush(userControl);
ctx.DrawRectangle(vb, new Pen(Brushes.Blue, 2), new Rect(new Point(0, 100), size));
}
rtb.Render(dv);
PngBitmapEncoder png = new PngBitmapEncoder();
png.Frames.Add(BitmapFrame.Create(rtb));
using (Stream fileStream = new FileStream(string.Format("{0}\\{1}.png", destFolder, fileName), FileMode.Create))
{
png.Save(fileStream);
}
}
錯誤
The calling thread cannot access this object because a different thread owns it.
在這一行
Rect bounds = VisualTreeHelper.GetDescendantBounds(userControl);
嗨,Mukesh Rawat 我試圖使用BackgroundWorker,但我不知道如何使用BackgroundWorker,因爲我是WPF多線程中的新手。你能幫我做一個關於我的問題的演示嗎? 非常感謝提前。 – user3286132