当前位置: 动力学知识库 > 问答 > 编程问答 >

multithreading - VB.Net thread seems to be running twice giving file access problems

问题描述:

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))

Next

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

res_file.WriteLine(DateTime.Now.ToString)

Next

res_file.Close()

End Sub

网友答案:

You're introducing an unnecessary Lambda here:

Sub() tp(x)

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: