Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

winforms - Updating UI from a different thread

I know this question has been asked before, but I feel it wasn't asked correctly.

I have an intensive operation and I'd like the UI to remain responsive. I've read a few posts that say Background worker is the best way to go, however, I think this assumes you have the source code to the intensive task.

I have a library that I have no source code for, the only way I can check on the progress is to attach to events that get fired and get information that way.

The example I saw on the MSDN site assumed one would have the source.

I know how to get progress (which is a percentage value) by attaching to events, but how do I get that value back to the UI?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The following answer is based on my gut feeling and have not actually done it a test with third party libs.

  • Call your third party lib code as usual you call in a simple background (not BackGroundWorker) thread.
  • Attach the library components' events to normal event handlers in your code (meant to update UI).
  • In the event handler code should look like this:

    private void EventHandler(object sender, DirtyEventArgs e)
    {
        if (myControl.InvokeRequired)
            myControl.Invoke(new MethodInvoker(MethodToUpdateUI), e);
        else
            MethodToUpdateUI(e);
    }
    
    private void MethodToUpdateUI(object obj) 
    {
        // Update UI
    }
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...