Reputation: 229
I'm trying to build an Outlook VSTO addin (using VB.Net) to do some time consuming data searching which is also have a Form Window of to show the current status of the task running, For this I want to use BackgroundWorker but I'm not sure how to achieve this in proper way. I tried to add a BackgroundWorker programmatically as in below code but its not working. whenever I open the Outlook in Visual Studio Debugger it straightly goes to Application is in break mode
where debugger is not giving any reference to the exact error. As ThisAddIn.vb
is a class file there was no drag-n-drop option to add the BackgroundWorker from visual studio Toolbox
. Please help. Thanks.
Public Class ThisAddIn
Shared WithEvents BackgroundWorker_Startup As BackgroundWorker
Public Async Sub ThisAddIn_Startup() Handles Me.Startup
Await Task.Delay(15000)
AddHandler BackgroundWorker_Startup.DoWork, AddressOf BackgroundWorker_Startup_DoWork
BackgroundWorker_Startup.RunWorkerAsync()
End Sub
Public Shared Sub BackgroundWorker_Startup_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker_Startup.DoWork
'Call a function
End Sub
Public Shared Sub BackgroundWorker_Startup_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker_Startup.ProgressChanged
Form1.Label.Text = (CType(e.UserState, String))
End Sub
Public Shared Sub BackgroundWorker_Startup_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker_Startup.RunWorkerCompleted
If (e.Error IsNot Nothing) Then
MsgBox(e.Error.Message)
End If
End Sub
End Class
Upvotes: 0
Views: 385
Reputation: 66276
Keep in mind that Outlook Object Model cannot be used from a thread other than the main one. Starting with Outlook 2016, it will raise an exception as soon as it detects access from a secondary thread. Your only options are Extended MAPI (C++ or Delphi) or Redemption (any language - I am its author) - its RDO family of objects can be used from a secondary thread (save the value of the Namespace.MAPIOBJECT
from OOM on the main thread, create a new instance of the RDOSession object on the secondary thread, set its MAPIOBJECT
property to the value saved on the main thread).
Windows controls also have thread affinity. In case of WinForms, that means you need to use Control.Invoke or Dispatcher object to make sure the code is executed on the main thread where the control was created.
Upvotes: 2