不同线程上的 WPF 屏幕“随机”冻结

本文关键字:随机 冻结 屏幕 WPF 线程 | 更新日期: 2023-09-27 18:35:47

我有一个问题,我已经有一个多星期了,我不知道为什么。

有一个等待屏幕,我将其放置在不同的线程中,因此即使代码正在执行大量工作,它也可以加载并显示它自己(当我在同一线程中执行 evrything 时,屏幕不会显示它是自我,我认为这是因为代码忙于做其他事情)

但是,它并不总是在某些时候冻结,并且仅在平板电脑上,它在我的PC上运行良好(至少我在PC上测试时没有注意到它冻结)。

我试图"破解"其中的一些解决方法,例如在等待屏幕上放置一个取消按钮,以便可以关闭它,但无法单击(好像它冻结并且没有响应)

1 次我也认为它带来了问题,因为我会在线程启动之前关闭它,所以我做了一个布尔值,如果线程仍在加载,我会说它是否仍在加载,如果我是,我试图关闭它我会添加一个事件列表器,以便在线程完成启动时关闭它。

无论如何,这是代码,我希望这里有人可以帮助我。

public partial class WaitWindow : Window
{
    //private static WaitWindow ww = new WaitWindow();
    private static Thread thread;
    private static event ThreadStartingEvent started;
    private delegate void ThreadStartingEvent(object sender, EventArgs e);
    public static bool disposable = false;
    private static bool startingThread;
    private static bool StartingThread
    {
        get
        {
            return startingThread;
        }
        set
        {
            startingThread = value;
            if (!startingThread && started != null)
            {
                started(null, new EventArgs());
            }
        }
    }
    // 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 WaitWindow()
    {
        InitializeComponent();
    }
    public static void BeginDisplay()
    {
        if (thread == null)
        {
            startingThread = true;
            thread = new Thread(() =>
            {
                WaitWindow ww = new WaitWindow();
                ww.Show();

                ww.Closed += (sender2, e2) =>
                ww.Dispatcher.InvokeShutdown();
                System.Windows.Threading.Dispatcher.Run();
            });
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            startingThread = false;
        }
    }
    public static void EndDisplay()
    {
        if (startingThread)
        {
            started += new ThreadStartingEvent(WaitWindow_started);
        }
        if (thread != null)
        {
            disposable = false;
            thread.Abort();
            thread = null;
        }
    }
    static void WaitWindow_started(object sender, EventArgs e)
    {
        thread.Abort();
        thread = null;
        started = null;
    }
    private void button1_Click(object sender, RoutedEventArgs e)
    {
        if (disposable)
        {
            disposable = false;
            thread.Abort();
            thread = null;
        }
    }
}

和 XAML 代码:

<Window x:Class="WpfApplication1.WaitWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
    Title="WaitWindow" WindowStyle="None" ResizeMode="NoResize" WindowStartupLocation="CenterScreen"
    Background="Transparent" AllowsTransparency="True" 
        Width="1024" Height="640">
    <Grid>
        <xctk:BusyIndicator Name="BusyBar" IsBusy="True" BusyContent="Even geduld a.u.b.">
        </xctk:BusyIndicator>
        <Button Name="button1" Width="28" HorizontalAlignment="Left" Margin="550,271,0,0" Height="28" VerticalAlignment="Top" Click="button1_Click">X</Button>
    </Grid>
</Window>

Maby 一些额外的信息:当我执行可能需要一些时间的任务(从远程数据库获取数据)时,我调用BeginDisplay()代码完成后,我调用EndDisplay()这对我来说似乎很明显,但我想提及它并没有什么坏处。

编辑:我可能应该提到我正在使用.NET Framework 3.5

不同线程上的 WPF 屏幕“随机”冻结

如果您正在执行后台异步任务,则需要创建一个 SynchronizationContext。也许这就是问题的原因?

// Create a thread
Thread newWindowThread = new Thread(new ThreadStart( () =>
{
    // Create our context, and install it:
    SynchronizationContext.SetSynchronizationContext(
        new DispatcherSynchronizationContext(
            Dispatcher.CurrentDispatcher));
    Window1 tempWindow = new Window1();
    // When the window closes, shut down the dispatcher
    tempWindow.Closed += (s,e) => 
       Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Background);
    tempWindow.Show();
    // Start the Dispatcher Processing
    System.Windows.Threading.Dispatcher.Run();
}));
// Set the apartment state
newWindowThread.SetApartmentState(ApartmentState.STA);
// Make the thread a background thread
newWindowThread.IsBackground = true;
// Start the thread
newWindowThread.Start();

这段代码是从这篇博客文章中捏出来的,值得好好读一读。

通常,您会将锁定 UI 的处理移动到后台线程,并使主线程可用于您通过 Dispatcher.Invoke() 返回的所有 UI 更新,因此您在这里拥有的是一个非常不同的实现。

我跳出的第一件事是使用Thread.Abort()我很确定 MSDN 文档基本上说不要使用它,除非您的线程没有其他停止方式。特别是,如果您中止了线程,则关闭打开的窗口将留下什么。这可能是你的问题吗?