Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Wpf 结束当前线程_Wpf_Multithreading - Fatal编程技术网

Wpf 结束当前线程

Wpf 结束当前线程,wpf,multithreading,Wpf,Multithreading,我有一个包含按钮的WPF应用程序。单击按钮时,我想显示一个新窗口,将一些UI内容加载到新窗口中,然后关闭它。我创建了一个新的UI线程,这样我的主应用程序就不会冻结。下面是我的代码: Thread thread = new Thread(() => { Window window = new Window(); window.WindowStyle = WindowStyle.None; window.B

我有一个包含
按钮的
WPF
应用程序。单击按钮时,我想显示一个新窗口,将一些
UI
内容加载到新窗口中,然后关闭它。我创建了一个新的
UI
线程,这样我的主应用程序就不会冻结。下面是我的代码:

Thread thread = new Thread(() =>
        {
            Window window = new Window();
            window.WindowStyle = WindowStyle.None;
            window.Background = Brushes.Transparent;
            window.AllowsTransparency = true;
            window.ShowInTaskbar = false;
            window.Show();

            //some UI activity

            window.Close();                
            Dispatcher.Run();                
        });
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        thread.Join();

        //some more activities
我预计线程将在
window.Close()之后结束,但它没有结束

//由于线程未结束,因此从未调用其他一些活动

是否有任何方法可以结束当前线程而不调用
线程.CurrentThread.Abort()

使用thread.Join()在等待创建
窗口的线程时,您将阻止主线程

private void Button_Click(object sender, RoutedEventArgs e)
{
    Thread thread = new Thread(() =>
    {
        Window1 w = new Window1();
        w.WindowStartupLocation = WindowStartupLocation.CenterScreen;
        w.Show();

        Task.Run(() =>
        {
            for (int i = 0; i < 10; i++)
            {
                 w.Dispatcher.Invoke(() => w.myTextBox.Text = i.ToString());
                 Thread.Sleep(200);
            }
            w.Dispatcher.InvokeShutdown();
        });

        Dispatcher.Run();
    });

    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
    thread.Join();

    Console.WriteLine("Window is now closed");
}

如果Window1的实例需要更多的工作,只需在那里添加帮助器方法,让它们完成自己的工作。确保在Window1的调度程序上完成所有工作

<Window x:Class="Stack9June2018EndCurrentThread.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Stack9June2018EndCurrentThread"
    mc:Ignorable="d"
    Title="Window1" Height="300" Width="300">
<Grid>
    <TextBlock x:Name="myTextBox"
               VerticalAlignment="Center"
               HorizontalAlignment="Center"/>
</Grid>