[英]VB.NET - ThreadPool and delegate in c# to VB.NET
Hey, how this is written in VB.NET? 嘿,这是用VB.NET编写的? This was an example I found on http://www.codeproject.com/KB/silverlight/SynchronousSilverlight.aspx .
这是我在http://www.codeproject.com/KB/silverlight/SynchronousSilverlight.aspx上找到的一个例子。
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);
});
May be a few syntax errors but I am sure you can resolve them. 可能是一些语法错误,但我相信你可以解决它们。
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
In VB10 (VS2010) you can do a rather literal translation: 在VB10(VS2010)中,您可以进行相当直接的翻译:
ThreadPool.QueueUserWorkItem(
Sub()
Console.WriteLine("Hello")
End Sub)
And note that there are not linecontinuations (_) necessary here. 请注意,此处不需要linecontinuations(_)。
But you probably want this for VS2008 and then you need to break out the delegate as a separate Sub or Function. 但是你可能想要VS2008这个,然后你需要将委托作为一个单独的Sub或Function分解。
Sub Main()
ThreadPool.QueueUserWorkItem(AddressOf CallBack, "Hello")
End Sub
Sub CallBack(ByVal state As Object)
Console.WriteLine(state)
End Sub
To provide a little explanation of the differences (other's have provided good code samples): 提供一些差异的解释(其他提供了良好的代码示例):
VB.NET doesn't support anonymous methods, which are supported in C# by using the delegate {}
syntax to define an inline method. VB.NET不支持匿名方法,这些方法在C#中通过使用
delegate {}
语法来定义内联方法。 To convert that syntax to VB.NET you have to move the contents of the anonymous inline method out into a normal method, then use a Delegate pointed at the extracted method to initiate the call. 要将该语法转换为VB.NET,您必须将匿名内联方法的内容移到普通方法中,然后使用指向提取方法的Delegate来启动调用。
When both are compiled they are essentially the same, since anonymous methods in C# are really only anonymous in their pre-compiled state (the compiler generates names for the methods and then treats them as first-class methods). 当两者都被编译时,它们本质上是相同的,因为C#中的匿名方法在其预编译状态下实际上只是匿名的(编译器为方法生成名称,然后将它们视为第一类方法)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.