2010-01-01 49 views
3

嘿,這是如何寫在VB.NET?這是我在http://www.codeproject.com/KB/silverlight/SynchronousSilverlight.aspx上找到的一個例子。VB.NET - ThreadPool和委託在C#VB.NET

ThreadPool.QueueUserWorkItem(delegate 
{ 
var channelFactory = new ChannelFactory<ISimpleService>("*"); 
var simpleService = channelFactory.CreateChannel(); 
var asyncResult = simpleService.BeginGetGreeting("Daniel", null, null); 
string greeting = null; 
try 
{ 
    greeting = simpleService.EndGetGreeting(asyncResult); 
} 
catch (Exception ex) 
{ 
    DisplayMessage(string.Format(
    "Unable to communicate with server. {0} {1}", 
    ex.Message, ex.StackTrace)); 
} 
DisplayGreeting(greeting); 
}); 

回答

3

可能是一些語法錯誤,但我相信你可以解決它們。

ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf GetGreeting)) 

Private Sub GetGreeting(o As Object) 
    Dim channelFactory = New ChannelFactory(Of ISimpleService)("*") 
    Dim simpleService = channelFactory.CreateChannel() 
    Dim asyncResult = simpleService.BeginGetGreeting("Daniel", Nothing, Nothing) 
    Dim greeting As String = Nothing 
    Begin Try 
     greeting = simpleService.EndGetGreeting(asyncResult) 
    Catch ex As Exception 
     DisplayMessage(String.Format("Unable to communicate with server. {0} {1}", ex.Message, ex.StackTrace)) 
    End Try 
    DisplayGreeting(greeting) 
End Sub 
+0

謝謝!我不直接在代碼項目上使用這個例子:)它主要是WaitCallback()我正在尋找! – sv88erik 2010-01-01 18:13:11

2

在VB10(VS2010),你可以做一個比較直譯:

ThreadPool.QueueUserWorkItem(
      Sub() 
      Console.WriteLine("Hello") 
      End Sub) 

而且請注意,有沒有必要linecontinuations(_)在這裏。

但是你可能想要這個VS2008,然後你需要分解委託作爲一個單獨的子或函數。

Sub Main() 
    ThreadPool.QueueUserWorkItem(AddressOf CallBack, "Hello") 
End Sub 

Sub CallBack(ByVal state As Object) 
    Console.WriteLine(state) 
End Sub 
+0

在VB10中使用匿名代理時,幾乎不會打字,這真是讓人慚愧。 (我很喜歡他們擺脫了那些荒謬的線路結局,儘管)。 – ChaosPandion 2010-01-01 17:35:03

0

提供的差異做一點解釋(他已經提供了良好的代碼示例):

VB.NET不支持匿名方法,這是在C#中使用delegate {}語法定義支持內聯方法。要將該語法轉換爲VB.NET,必須將匿名內聯方法的內容移出到普通方法中,然後使用指向提取方法的委託來發起調用。

當兩者都編譯時,它們基本上是一樣的,因爲C#中的匿名方法在預編譯狀態下實際上只是匿名的(編譯器爲方法生成名稱,然後將它們視爲第一類方法)。