I have some very basic code that takes a list of strings and a new thread is created per string.
The thread then writes a file named with the string so should be unique but I get access violations.
I try the debugger option in VS 2010 and it doesn't give me the file access problems when I step through but it writes two lines per loop so I am assuming it still has a problem with running the thread twice
Code to call the thread:
For Each x In x_list
Dim trd as new Thread(DirectCast(Sub() tp(x), ThreadStart))
Code for thread:
Private Sub tp(ByVal x_in As String)
Dim res_file As New StreamWriter("C:\result_" + x_in + ".txt", True)
For i = 1 to 5
You're introducing an unnecessary Lambda here:
And then you're falling foul of the same well known issue from C# - that what you're capturing is the variable that keeps changing until it's set to the last value in the loop.1
Try instead just:
For Each x In x_list Dim trd as new Thread(DirectCast(tp, ParameterizedThreadStart)) trd.Start(x) 'TODO - Does trd get stored anywhere? Next
1 See e.g. Closing over the loop variable considered harmful which discusses how there's a change for C#5, but I don't think there's a corresponding change for VB.Net.