We found that if a COM interface is called inside the DoWorkEventHandler, it will cost more time than the time spent outside.
For example, we first create and expose a com interface like following.
STDMETHODIMP_(HRESULT __stdcall) CTemp::Number1(LONG * __result)
{
*__result = 1;
return S_OK;
}
And then, call Number1 in a VB project like follwing.
Imports System.ComponentModel
Imports System.IO
Imports System.Runtime.InteropServices
Public Class MainForm
Public Sub New()
InitializeComponent()
End Sub
Private Sub MainForm_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
End Sub
Private Sub btnRun_Click_async(sender As Object, e As EventArgs) Handles btnRun.Click
btnRun.Enabled = False
Dim stopwatch As New Stopwatch
Dim oTestCalss As New ComTestLib.Temp
For t = 1 To 10000
stopwatch.Start()
oTestCalss.Number1()
stopwatch.Stop()
Next
MsgBox(String.Format("OutDoWork::Measured elapsed time is {0}.", stopwatch.Elapsed.ToString("mm\:ss\.fff")))
stopwatch.Reset()
Dim doWorkHandler As DoWorkEventHandler =
Sub()
For t = 1 To 10000
stopwatch.Start()
oTestCalss.Number1()
stopwatch.Stop()
Next
MsgBox(String.Format("InDoWork::Measured elapsed time is {0}.", stopwatch.Elapsed.ToString("mm\:ss\.fff")))
End Sub
stopwatch.Reset()
AddHandler BackgroundWorker.DoWork, doWorkHandler
BackgroundWorker.RunWorkerAsync()
End Sub
End Class
The result is shown in the attachment. No matter 32bit com or 64bit com, calling 10,000 times com interface out of the handler will only cost few milliseconds, but in the handler, it takes more time obviously.
So, the question is, why is there such a big performance difference between calling the com interface inside and outside the DoWorkEventHandler?