using System;
using System.Windows.Threading;
public class DispatcherExample
{
private Dispatcher dispatcher;
public DispatcherExample(Dispatcher dispatcher)
{
this.dispatcher = dispatcher;
}
public void UpdateUI()
{
// 检查当前线程是否是UI线程
if (dispatcher.CheckAccess())
{
// 如果是在UI线程中,直接更新UI
Console.WriteLine("Updating UI from the UI thread.");
}
else
{
// 如果不在UI线程中,使用Dispatcher将操作调度到UI线程
dispatcher.Invoke(() =>
{
Console.WriteLine("Updating UI from a background thread using Dispatcher.");
});
}
}
}
// 使用示例
public class Program
{
public static void Main()
{
// 创建一个Dispatcher实例(通常在WPF应用程序中,窗体或控件已经有一个Dispatcher)
Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
var example = new DispatcherExample(dispatcher);
// 模拟从非UI线程调用
System.Threading.ThreadPool.QueueUserWorkItem((_) =>
{
example.UpdateUI();
});
// 保持主线程运行,以便后台线程可以执行
System.Threading.Thread.Sleep(1000);
}
}
Dispatcher 是 WPF 中用于管理 UI 线程和后台线程之间通信的核心类。它确保只有 UI 线程可以更新 UI 组件,而其他线程可以通过 Dispatcher 将操作调度到 UI 线程。Invoke 方法将操作调度到 UI 线程。UpdateUI 方法中,我们首先检查当前线程是否是 UI 线程。如果不是,则使用 dispatcher.Invoke 将更新操作调度到 UI 线程。上一篇:c# gethashcode
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站