Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

c# - Thread-safe 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();
        }
    }

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

EDIT

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

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...