不幸的是,线程和任务对我来说是一个很大的谜。
必须在与 DependencyObject 相同的线程上创建 DependencySource。
我正在努力避免用户界面冻结。我的方法是在线程中完成工作,然后使用线程的输出设置属性。
我有一个基类Job。基本上它是一个包装器,用一个开始一个新线程Input and Output多变的。我启动一个新线程,等到工作完成并尝试将其设置为我的属性MyFoo。但这是行不通的。请参阅上面引用的错误消息。
How can I use a thread* without blocking the UI and set the result to an property in WPF?
* I actually don't care if it is a thread, a task or whatever as long as it is not blocking my UI.
// ...
FooJob job = new FooJob {Input = input};
job.Start();
while (!job.IsDone) Wait(0.05);
MyFoo = (BitmapSource) job.Output;
我尝试的是将输出设置为我的字段而不是我的属性并调用属性改变时手动。
这里是实际的包装类
public class Job {
public object Output;
public object Input;
private bool _isDone;
private readonly object _handle = new object();
private Thread _thread;
public bool IsDone {
get {
bool tmp;
lock (_handle) {
tmp = _isDone;
}
return tmp;
}
set {
lock (_handle) {
_isDone = value;
}
}
}
public virtual void Start() {
_thread = new Thread(Run);
_thread.Start();
}
protected virtual void ThreadFunction() {}
private void Run() {
ThreadFunction();
IsDone = true;
}
}
您收到异常的原因必须在与 DependencyObject 相同的线程上创建 DependencySource。是一个迹象表明BitmapSource
已在新线程上创建,您将无法绑定BitmapSource
到 UI,除非您在 UI 线程上创建它。然而,因为BitmapSource
是可冻结的,您也可以“冻结”它以删除它的线程关联性。所以如果你真的需要创建一个BitmapSource
在另一个线程上你将不得不调用Freeze
on the BitmapSource
在您可以将其绑定到 UI 之前。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)