Converting C# ThreadStart Delegate to VB.NET
I need to convert C# code to VB.NET code (based on .NET 3.5 and VS 2008),
but I am having problem converting C# delegates to its VB.NET equivalent.
The C# code I want to convert, which works properly, is here:
protected override void OnOwnerInitialized()
{
if (!MobileApplication.Current.Dispatcher.CheckAccess())
{
// MobileApplication.Current is some 3rd party API
// MobileApplication.Current.Dispatcher is type
System.Windows.Threading.Dispatcher
MobileApplication.Current.Dispatcher.BeginInvoke
(
(System.Threading.ThreadStart)delegate()
{
OnOwnerInitialized();
}
);
return;
}
DoSomething();
}
I translated to the following VB.NET code but it does not work:
Protected Overrides Sub OnOwnerInitialized()
If Not MobileApplication.Current.Dispatcher.CheckAccess() Then
MobileApplication.Current.Dispatcher.BeginInvoke(Function() New
System.Threading.ThreadStart(AddressOf OnOwnerInitialized))
Return
End If
' I also tried the following but I get thread related errors elsewhere
in code
'If ((Not MobileApplication.Current.Dispatcher.CheckAccess()) And (Not
threadStarted)) Then
' Dim newThread As New Thread(AddressOf OnOwnerInitialized)
' newThread.Start()
' threadStarted = True ' this is a shared / static variable
' Return
'End If
DoSomething()
End Sub
With the C# code, OnOwnerInitialized() gets called twice. On the first
call, the function exists with the 'return;' statement; on the second time
'DoSomething() is called. This is the correct behaviour. However, in the
VB.NET code, it only runs once, the code does returns on the 'Return'
statement and that is it (I believe my translated VB.NET code is not
invoking the thread correct. The code below is the C# code).
Thanks.
No comments:
Post a Comment