从任务更新标签

Update a label from a task

我正在尝试在我的程序中执行任务。我启动了一个将生成日志文件的任务,之后,我想更新标签以显示 "Log sucessfully saved".

这是我的代码

Private Function Createlog(ByVal mylist As List(Of classTest))
        Dim sw As New StreamWriter("log_list.log")
        For index = 1 To mylist.Count - 1
            sw.WriteLine(mylist(index).comments)
        Next
        sw.Close()
        Try
            Me.Invoke(UpdateLabel("Log sucessfully saved"))
        Catch ex As Exception

        End Try
        Return 1
    End Function

    Private Function UpdateLabel(ByVal text As String)
        Label1.Text = text
        Return 1
    End Function

我从 Load() 中的主窗体启动任务:

 Dim tasktest = Task(Of Integer).Factory.StartNew(Function() Createlog(theList))

(不知道是用工厂好还是声明为任务然后task.Start())

我在更新标签时遇到错误:

Cross-thread operation not valid: Control 'Label1' accessed from a thread other than the thread it was created on.

能否请您解释一下为什么它不适用于 invoke 方法?你有替代解决方案吗?

感谢您的帮助

首先,UpdateLabel 应该是 Sub,而不是 Function。二、这一行是错误的:

Me.Invoke(UpdateLabel("Log sucessfully saved"))

再读一遍。您按顺序执行 UpdateLabel 函数,然后将该函数的结果传递给 Me.Invoke(如果您使用 Sub 而不是 Function,编译器应该警告你关于这个错误)。

这不会引发任何编译器错误,因为在没有 As [Type] 的情况下声明的 Function 默认为 As Object,可以转换为任何内容。应该是:

Me.Invoke(Sub()
              UpdateLabel("Log sucessfully saved")
          End Sub)

为了简化,您的代码可以这样重写:

Private Sub Createlog(ByVal mylist As List(Of classTest))
    Dim sw As New StreamWriter("log_list.log")
    For index = 1 To mylist.Count - 1
        sw.WriteLine(mylist(index).comments)
    Next
    sw.Close()
    Me.Invoke(Sub()
                  Label1.Text = "Log sucessfully saved"
              End Sub)
End Sub