当调用是非线程时,在wpf中显示“Please wait”窗口的替​​代方法是什么

时间:2011-07-23 19:01:30

标签: wpf

最近我需要在wpf应用程序中实现请等待对话框。我发现下面的代码。它真的很好但它总是在saprate线程中打开一个窗口并保持位置。以下代码还有其他任何改动吗?而我的代码请求是非线程的。

private void NewWindowThread<T,P>(Func<P, T> constructor, P param) where T : Window
{
Thread thread = new Thread(() =>
{
T w = constructor(param);
w.Show();
w.Closed += (sender, e) => w.Dispatcher.InvokeShutdown();
System.Windows.Threading.Dispatcher.Run();
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}

调用上面的方法使用下面的行。加载窗口是你要在对话框中显示的窗口(请等待.windows)

   string t = "Please Wait…";
NewWindowThread<LoadingWindow, string>(c => new LoadingWindow(c), t);

2 个答案:

答案 0 :(得分:2)

阻止ui线程从来都不是一个好主意,但它越来越不是一个坏主意。

Windows会告诉用户您的应用停止响应。这可能会促使他们强迫您的申请。如果渲染进度条,它们将丢失动画效果,并且它们可能呈现不正确。在WPF中,gui动画将停止。

使用后台线程进行繁重的处理,如果需要在主线程使用的对象中写回数据,请将它们编组回gui线程。 BackgroundWorker在那里很有用。

答案 1 :(得分:2)

这可能会帮助你。

public partial class Splash : Window
    {
        private static Splash splash = new Splash();

        // To refresh the UI immediately
        private delegate void RefreshDelegate();
        private static void Refresh(DependencyObject obj)
        {
            obj.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Render,
                (RefreshDelegate)delegate { });
        }

        public Splash()
        {
            InitializeComponent();
        }

        public static void BeginDisplay()
        {
            splash.Show();
        }

        public static void EndDisplay()
        {
            splash.Close();
        }

        public static void Loading(string test)
        {
            splash.statuslbl.Content = test;
            Refresh(splash.statuslbl);
        }
    }

使用上面的代码

       Splash.BeginDisplay();

// Setting the status to show the application is still loading data
        Splash.Loading("Connecting...");
        // Set to sleep to simulate long running process
        Thread.Sleep(1500);
        Splash.Loading("Retrieving....");
        Thread.Sleep(1500);
        Splash.Loading("Success....");
        Thread.Sleep(1500);
        Splash.EndDisplay();