3

I do not fully understand what the STATHREAD attribute does http://msdn.microsoft.com/en-us/library/system.stathreadattribute.aspx. Please see the code below:

Imports Project1
Imports System.Threading

Public Class Form1

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim t1 As New Thread(AddressOf PersonTest.Test2)
        Dim t2 As New Thread(AddressOf PersonTest.Test2)
        Dim t3 As New Thread(AddressOf PersonTest.Test2)
        t1.Name = "Test1"
        t2.Name = "Test2"
        t3.Name = "Test3"
        t1.Start()
        t2.Start()
        t3.Start()
    End Sub

End Class

The code explicitly creates three threads, so there are four threads in total i.e. the main thread, t1,t2 and t3.

Is the STATHREAD required for a Windows Form app that has one thread i.e. the main threads?

w0051977
  • 15,099
  • 32
  • 152
  • 329

1 Answers1

2

STAThread is for the primary UI thread.

In Windows, the Single Threaded Apartment (STA) implies that (in simple terms) a Windows message pump will cooperatively manage the UI.

The attribute tells the app to create an STA thread effectively for the first/main UI thread. The other threads are effectively running in parallel to this thread and they need to ensure that when they make calls to UI components, they pass them as messages through the message pump in STA.

Now lots of people will talk about it being a COM requirement and this is true. This is because at its core, the STA threading model for COM uses Windows message pumps and is required for communication with a lot of the Windows UI.

There is good answer here too: Why do all Winforms programs require the [STAThread] attribute?

Community
  • 1
  • 1
Preet Sangha
  • 64,563
  • 18
  • 145
  • 216
  • Thanks. Are you able to provide an example or link to an example that demonstrates a risk when ommiting STATHREAD in a single threaded VB.NET app? – w0051977 Jun 05 '13 at 21:53
  • One side effect is that any GUI control that depends on STAThreading model will not operate correctly. This is often the case with .NET components that are wrappers for built in windows components. – DarrenMB Jun 05 '13 at 23:09