我正在主线程上执行一些繁重的计算,并且这些计算无法在单独的线程上运行。使用后台线程显示“Busy Indicator”
我想上的应用程序的用户界面显示一个“忙指示符”(即,纺丝插件)时这些计算都在运行。因此,我无法在主线程上显示忙碌指示符,因为在这些计算运行时UI被锁定。
要解决这个问题,我想移动繁忙指示器单独的线程。在this post的帮助下,我可以将忙指标放在单独的线程上。但是,我无法与此线程通信以启动或停止繁忙指示器。
private HostVisual CreateBusyIndicatorOnWorkerThread()
{
// Create the HostVisual that will "contain" the VisualTarget
// on the worker thread.
HostVisual hostVisual = new HostVisual();
Thread thread = new Thread(new ParameterizedThreadStart(BusyIndicatorWorkerThread));
thread.ApartmentState = ApartmentState.STA;
thread.IsBackground = true;
thread.Start(hostVisual);
// Wait for the worker thread to spin up and create the VisualTarget.
s_event.WaitOne();
return hostVisual;
}
private static AutoResetEvent s_event = new AutoResetEvent(false);
private void BusyIndicatorWorkerThread(object arg)
{
// Create the VisualTargetPresentationSource and then signal the
// calling thread, so that it can continue without waiting for us.
HostVisual hostVisual = (HostVisual)arg;
VisualTargetPresentationSource visualTargetPS = new VisualTargetPresentationSource(hostVisual);
s_event.Set();
// Create a MediaElement and use it as the root visual for the
// VisualTarget.
visualTargetPS.RootVisual = CreateBusyIndicator();
// Run a dispatcher for this worker thread. This is the central
// processing loop for WPF.
System.Windows.Threading.Dispatcher.Run();
}
private FrameworkElement CreateBusyIndicator()
{
var busyIndicator = new MyBusyIndicator();
//busyIndicator.DataContext = this.
Binding myBinding = new Binding("IsBusy");
myBinding.Source = this;
busyIndicator.SetBinding(MyBusyIndicator.IsBusyProperty, myBinding);
}
我总是得到一个异常“因为不同的线程拥有它调用线程不能访问该对象”。这是因为我正尝试从主线程更新繁忙指示符,而繁忙指示符由另一个线程拥有。
我也试图在this article给出的方法,
private void CreateAndShowContent()
{
Dispatcher = Dispatcher.CurrentDispatcher;
VisualTargetPresentationSource source =
new VisualTargetPresentationSource(_hostVisual);
_sync.Set();
source.RootVisual = _createContent();
DesiredSize = source.DesiredSize;
_invalidateMeasure();
Dispatcher.Run();
source.Dispose();
}
但是这种方法Dispatcher.Run()没有任何反应,直到计算完成后,然后显示繁忙指示器。
我想从主线程进行通信,以具有繁忙指示符的线程。有没有人有办法?
请提供一个原因,为什么这些操作无法在任何其他线程上运行,然后在UI线程?我没有看到任何实际的原因。 – ElGauchooo
而不是在UI线程中执行非UI工作并在非UI线程中执行UI工作,将其逆转。您的用户界面是否在UI线程中工作,您的非UI工作是否在非UI线程中工作?这只是您使用的整个系统的设计。 – Servy
我正在使用第三方库进行计算并检查调用者线程是否是主线程。所以我们不能改变他们的实现,所以我们必须在不同的线程上做我们的UI。 – Ahmed