为什么这两种方法中的线程不同?

时间:2011-01-23 22:33:50

标签: vb.net multithreading visual-studio visual-studio-2010

看看下面的代码。

在这里,我创建一个线程,设置其名称,然后启动它:

Private Sub fileCreated(sender As Object, e As FileSystemEventArgs)
    Dim processFileThread As Thread = New Thread(AddressOf fileCreatedHelper)
    processFileThread.Name = e.FullPath
    processFileThread.Start()
End Sub

这是线程的子:

Private Sub fileCreatedHelper()
    If Me.InvokeRequired Then
        Me.Invoke(New MethodInvoker(AddressOf fileCreatedHelper))
    Else
        Dim currentThread = Thread.CurrentThread ' NOT WORKING!
        Dim fileName = currentThread.Name
        ' do more stuff that requires fileName
    End If
End Sub

fileCreatedHelper中,Thread.CurrentThread没有得到我上面创建的主题。为什么是这样?当我将断点放入并查看ManagedThreadIds时,它们是不同的。

思想/想法?谢谢!

2 个答案:

答案 0 :(得分:1)

通过调用New Thread(...).Start(),您正在创建一个新主题。

通过调用Me.Invoke(...),您将在UI线程上执行代码,并使新线程等待UI线程上的代码完成。

答案 1 :(得分:1)

因为当您在ELSE分支中时,您已被调用并且CurrentThread是主(GUI)线程。不是您在步骤1中创建的主题。

您需要一个额外的方法:

  • 一个在单独的线程上处理文件。考虑另一种传递文件名的mecahnism。
  • 一个在GUI中“使用”结果。那个需要InvokeReq / Invoke模式。