本文介绍了线程安全的Form.Show的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个需要,因为它是被用来报告异步套接字输入的状态是线程安全的敬酒。我试图使它线程安全的,但祝酒词依然锁定。

I'm writing a Toast that needs to be thread-safe as it's being used to report the status of asynchronous socket input. I've tried to make it thread-safe but the toasts are still locking up.

    public static void Show( string message ) {
        Toast toast = new Toast( message );
        toast.ShowAction();
    }

    private delegate void InvokeCallback();

    public void ShowAction() {
        if ( InvokeRequired ) {
            Invoke( new InvokeCallback( ShowAction ) );
        }
        else {
            Show();
        }
    }



我希望能够很容易地显示它们像消息框,即 Toast.Show(状态改为); 。任何帮助将不胜感激。

I want to be able to display them easily like a message box, i.e. Toast.Show("Status changed");. Any help would be greatly appreciated.

推荐答案

您的问题是一个事实,即吐司正在创建另一个线程。什么你可能需要做的是在主UI线程上的目标在那里你可以的invoke()创建并显示吐司,保持所有UI在同一个线程。

Your issue is the fact that the Toast is being CREATED on another thread. What you'll likely need to do is have a "target" on the main UI thread where you can Invoke() the creation AND showing of the Toast, keeping all UI on the same thread.

修改

如果您需要能够把这个在另一个线程,你唯一的选择是创建一个消息循环另一个线程。

If you need to be able to keep this on another thread, your only other option is to create another thread with a message loop.

Thread t = new Thread();

t.SetApartmentState(ApartmentState.STA) // Required for a UI thread

对于分派的任务和消息,以该线程的执行,我会留给你来决定。你需要调用 Application.Run()在它以启动消息循环的开始。

As to the implementation of dispatching tasks and messages to this thread, I'll leave that up to you. You'll need to call Application.Run() at the start of it in order to start your message loop.

和一如既往,你必须确保以的invoke()从你的面包(或在此线程任何东西)可以与主UI交互的任何操作主题。

And, as always, you'll have to be sure to Invoke() any operations from your Toast (or anything on this thread) that may interact with the main UI thread.

这篇关于线程安全的Form.Show的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 17:42