Update UI form from worker thread

后端 未结 2 634
没有蜡笔的小新
没有蜡笔的小新 2020-12-11 23:38

I am new to multi-threading in VB.NET and have come across a problem whereby I am wanting to append text to a text box on a form from a service thread running in the backgro

2条回答
  •  悲哀的现实
    2020-12-12 00:22

    I have a form named testDebug...

    If testDebug.InvokeRequired Then
    

    This is a classic trap in VB.NET programming. Set a breakpoint on the If statement. Notice how it returns False, even though you know that the code is running on another thread?

    InvokeRequired is an instance property of a Form. But testDebug is a class name, not a reference to an instance of a form of type testDebug. That this is possible in VB.NET has gotten a lot of VB.NET programmers in deep trouble. It is an anachronism carried over from VB6. It completely falls apart and blows up in your face when you do this in a thread. You'll get a new instance of the form, instead of the one that the user is looking at. One that isn't visible because its Show() was never called. And otherwise dead as a doornail since the thread isn't running a message loop.

    I answered this question several times already, with the recommended fix. I'll just refer you to them rather than rehashing it here:

    • Form is not updating, after custom class event is fired

    • Accessing controls between forms

提交回复
热议问题