I have a WPF app and in the main form, user is allowed to select few files(Excel) and then click a button to do a data extraction and uploading them to a database. Things work fine.
Now I wanted to implement a busy indicator.
So what I have done is, declare a BackgroundWorker thread and do my database uploading (which takes time) as a background thread. The busy indicator is set accordingly when thread start and completes. The Issue is inside my upload process, I access Clipboard to print some messages. So I ran in to the following error which is obvious.
"Current thread must be set to single thread apartment (STA) mode before OLE calls can be made."
BackgroundWorker is by default MTA. So what is the best way to overcome this issue?
Code:
Public WithEvents BgWorker As BackgroundWorker = New BackgroundWorker()
Private Sub MainWindow_Loaded() Handles Me.Loaded
AddHandler BgWorker.DoWork, AddressOf ExtractData
AddHandler BgWorker.RunWorkerCompleted, AddressOf BgWorker_RunWorkerCompleted
End Sub
Private Sub btnExtract_Click(sender As Object, e As RoutedEventArgs)
.....
Try
.....
Me.busyIndicator.IsBusy = True
BgWorker.RunWorkerAsync(Me.cmbFormats.SelectedItem.ToString.Trim())
Catch ex As Exception
Utility.Message.ErrorMessage(ex)
End Try
End Sub
completed event:
Private Sub BgWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
busyIndicator.IsBusy = False
End Sub
DoWork:
Private Sub ExtractData(sender As Object, e As DoWorkEventArgs)
Dim exformat As IExtractor = New FormatFactory().CreateInstance(e.Argument.ToString())
If (exformat.FeedToDb(filename)) Then
Utility.Message.SuccessMessage("Successfully Extracted to database")
Else
End If
End Sub
Utility.Message.SuccessMessage :
Public Shared Sub SuccessMessage(msg As String)
Dim M As New Text.StringBuilder
M.AppendLine()
M.AppendLine(msg)
M.AppendLine()
Clipboard.Clear() 'problem with MTA
Clipboard.SetText(M.ToString)
MsgBox(M.ToString, MsgBoxStyle.Information, "FF IT")
End Sub