Force multi-threaded VB.NET class to display results on a single form

前端 未结 4 1839
走了就别回头了
走了就别回头了 2020-12-22 07:10

I have a windows form application that uses a Shared class to house all of the common objects for the application. The settings class has a collection of objects that do thi

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-22 07:41

    I think it is a threading problem too. Are you using Control.Invoke() in your event handler? .NET usually catches violations when you debug the app but there are cases it can't. NotifyIcon is one of them, there is no window handle to check thread affinity.

    Edit after OP changed question:

    A classic VB.NET trap is to reference a Form instance by its type name. Like Form1.NotifyIcon1.Something. That doesn't work as expected when you use threading. It will create a new instance of the Form1 class, not use the existing instance. That instance isn't visible (Show() was never called) and is otherwise dead as a doornail since it is running on thread that doesn't pump a message loop. Seeing a second icon appear is a dead give-away. So is getting InvokeRequired = False when you know you are using it from a thread.

    You must use a reference to the existing form instance. If that is hard to come by (you usually pass "Me" as an argument to the class constructor), you can use Application.OpenForms:

      Dim main As Form1 = CType(Application.OpenForms(0), Form1)
      if (main.InvokeRequired)
        ' etc...
    

提交回复
热议问题