将C#ThreadStart委托转换为VB.NET

时间:2013-09-09 05:54:59

标签: c# vb.net multithreading delegates

我需要将C#代码转换为VB.NET代码(基于.NET 3.5和VS 2008),但是我在将C#代理转换为VB.NET等效时遇到了问题。

我想要转换的C#代码,它正常工作,在这里:

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();
}

我翻译成以下VB.NET代码,但它不起作用:

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

使用C#代码,OnOwnerInitialized()被调用两次。在第一次调用时,函数与'return;'一起存在声明;在第二次'DoSomething()被调用。这是正确的行为。但是,在VB.NET代码中,它只运行一次,代码确实返回'Return'语句,就是它(我相信我翻译的VB.NET代码没有调用正确的线程。下面的代码是C#码)。

感谢。

2 个答案:

答案 0 :(得分:0)

看起来你可以缩短它。

http://msdn.microsoft.com/en-us/library/57s77029(v=vs.100).aspx?appId=Dev10IDEF1&l=EN-US&k=k(SYSTEM.THREADING.THREADSTART)%3bk(VS.OBJECTBROWSER)%3bk(TargetFrameworkMoniker-” NETFRAMEWORK,VERSION%3dV4.0" 。)及RD =真安培; CS-保存琅= 1&安培; CS琅= VB#代码片断-2

Protected Overrides Sub OnOwnerInitialized()
    If Not MobileApplication.Current.Dispatcher.CheckAccess() Then
        MobileApplication.Current.Dispatcher.BeginInvoke(AddressOf OnOwnerInitialized)
        Return
    End If

    DoSomething()
End Sub

答案 1 :(得分:0)

我想我明白了:

Protected Overrides Sub OnOwnerInitialized()
    If Not MobileApplication.Current.Dispatcher.CheckAccess() Then
        MobileApplication.Current.Dispatcher.BeginInvoke(DirectCast(Function() DoSomethingWrapper(), System.Threading.ThreadStart))
        Return
    End If
End If


Private Function DoSomethingWrapper() As Boolean
    DoSomething()
    Return True ' dummy value to satisfy that this is a function
End If

基本上,我认为因为我使用的是.NET 3.5,所以下面的行只能使用一个函数,而不是一个子函数:

    MobileApplication.Current.Dispatcher.BeginInvoke(DirectCast(Function() RunExtension(), System.Threading.ThreadStart))

现在因为OnOwnerInitialized()必须是一个sub(因为它覆盖了一个sub),并且BeginInvoke必须接受一个函数,我只是添加了一个包装函数来包装DoSomething(),所以OnOwnerInitialized()可以调用DoSomething( )通过包装函数。