Backgroundworker不应该避免主窗口冻结吗?

时间:2016-02-29 23:07:51

标签: vb.net visual-studio backgroundworker office-addins

我正在尝试为Office加载项测试Backgroundworker。简单的代码是这样的:

Imports Microsoft.Office.Tools.Ribbon
Imports System.ComponentModel
Imports System.Windows.Forms

Public Class Ribbon1
Dim f As New Form1
Dim bw As BackgroundWorker = New BackgroundWorker


Private Sub Ribbon1_Load(ByVal sender As System.Object, ByVal e As RibbonUIEventArgs) Handles MyBase.Load
    AddHandler bw.DoWork, AddressOf bw_DoWork
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As Microsoft.Office.Tools.Ribbon.RibbonControlEventArgs) Handles Button1.Click
    System.Threading.SynchronizationContext.SetSynchronizationContext(New WindowsFormsSynchronizationContext())
    bw.RunWorkerAsync()
End Sub

Private Sub bw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
    For x = 1 To 100
        f.Label1.Text = x.ToString
    Next
    f.Show()
End Sub
End Class

我将backgroundworker理解为可以与主应用程序一起运行的工具。但是主要应用程序冻结(或被禁用),直到后台工作者完成其工作。这是正常的吗?

1 个答案:

答案 0 :(得分:1)

如果存在跨线程访问,则需要调用。 并且不需要System.Threading.SynchronizationContext.SetSynchronizationContext(New WindowsFormsSynchronizationContext())

做这样的事情。

Private Sub bw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
    For x = 1 To 100
        Me.Invoke(Sub() f.Label1.Text = x.ToString)
    Next
    Me.Invoke(Sub() f.Show())
End Sub