这些都不起作用:
_uiDispatcher.Invoke(() => { });
_uiDispatcher.Invoke(delegate() { });
Run Code Online (Sandbox Code Playgroud)
我想要做的就是在我的主UI线程上调用内联方法.所以我在主线程上调用了这个:
_uiDispatcher = Dispatcher.CurrentDispatcher;
Run Code Online (Sandbox Code Playgroud)
现在我想从另一个线程在该线程上执行一些代码.我该怎么做?我使用了错误的语法吗?
请注意,这不是 WPF应用程序; 我引用了WindowsBase
所以我可以访问Dispatcher
该类.
为什么我不能在以下代码中创建CroppedBitmap?我有一个例外:
调用线程无法访问此对象,因为另一个线程拥有它.
如果我将代码更改为
CroppedBitmap cb = new CroppedBitmap(new WriteableBitmap(bf), new Int32Rect(1, 1, 5, 5));
Run Code Online (Sandbox Code Playgroud)
异常消失了吗?为什么?
代码1,例外情况cb.Freeze()
:
public MainWindow()
{
InitializeComponent();
ThreadPool.QueueUserWorkItem((o) =>
{
//load a large image file
var bf = BitmapFrame.Create(
new Uri("D:\\1172735642.jpg"),
BitmapCreateOptions.None,
BitmapCacheOption.None);
bf.Freeze();
Dispatcher.BeginInvoke(
new Action(() =>
{
CroppedBitmap cb = new CroppedBitmap(bf, new Int32Rect(1,1,5,5));
cb.Freeze();
//set Image's source to cb....
}),
DispatcherPriority.ApplicationIdle);
}
);
}
Run Code Online (Sandbox Code Playgroud)
代码2,有效:
ThreadPool.QueueUserWorkItem((o) =>
{
var bf = BitmapFrame.Create(
new Uri("D:\\1172740755.jpg"),
BitmapCreateOptions.None,
//BitmapCreateOptions.DelayCreation,
BitmapCacheOption.None);
bf.Freeze();
var wb = new …
Run Code Online (Sandbox Code Playgroud)