Mehmet Keskin
Mehmet Keskin

Reputation: 25

Shouldn't Backgroundworker avoid main windows freeze?

I am trying to test the Backgroundworker for an Office Add-In. The simple code is like this :

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

I understand the backgroundworker as a tool which can run together with the main application. But the main application freezes (or is disabled) until the backgroundworker has finished its work. Is this normal ?

Upvotes: 0

Views: 59

Answers (1)

Sarvesh Mishra
Sarvesh Mishra

Reputation: 2072

An invoke is required if cross thread access is there. And there is no requirement for System.Threading.SynchronizationContext.SetSynchronizationContext(New WindowsFormsSynchronizationContext())

Do something like this.

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

Upvotes: 1

Related Questions