我读到过C#版本是这样的:
Application.Current.Dispatcher.Invoke(
DispatcherPriority.Background,
new Action(delegate { }));但是,我不知道如何将空委托放入VB.NET中,因为VB.NET似乎不支持匿名方法。想法?
编辑:有可能是这样吗?
Application.Current.Dispatcher.Invoke(
DispatcherPriority.Background,
New Action(Sub()
End Sub))发布于 2010-04-19 20:47:06
VB.NET确实支持匿名委托,但仅支持单语句函数。(在.NET 4的VB10中增加了多语句匿名函数和匿名Sub)
为了提供上下文,DoEvents被设计为允许单线程环境在工作完成时更新UI和处理其他Windows消息。从另一个线程调用DoEvents应该没有任何好处(或者,正如您在这里所做的,通过在dispatcher上执行"null“函数间接地实现这一点),因为UI线程应该会自动更新。
不过,为了回答您的问题,最简单的选择如下所示:
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, _
New Action(Function() 7))但是,再说一次,我看不出这会有什么实际的效果。
如果您要寻找的只是如何在UI线程上执行代码(如Windows forms中的Control.Invoke ),那么Dispatcher.Invoke (这就是您正在使用的)是正确的,那么您只需将您的内联匿名方法转换为谨慎的函数,并将这些函数作为委托进行传递。也许有一些你可以通过匿名离开而逃脱惩罚。例如,如果您所做的只是更新进度条,则可以执行以下操作:
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, _
New Action(Function() progressBar.Value = 100))这是因为所有赋值都会返回存储在赋值左侧的值。但是,您不能像这样简单地调用sub (除非SomeFunctionName返回值,否则以下代码将不会编译):
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, _
New Action(Function() SomeFunctionName(params)))换句话说,C#代码中的任何匿名委托都符合以下条件:
然后,您必须为这些函数创建函数,并将委托传递给这些函数,而不是像在C#中那样内联代码。
发布于 2010-04-20 14:18:14
如果您希望在UI上刷新某些内容,则可以简单地调用此方法:
System.Windows.Forms.Application.DoEvents我们在WPF窗口和XBAP应用程序上使用它。
发布于 2010-04-20 13:54:32
这里有两个问题,所以我将添加两个答案。在这里,我回答“如何在WPF中做DoEvents”。Bea Stollnitz在her blog上介绍了这一点,下面是VB的代码:
publicShared Sub WaitForPriority(priority As DispatcherPriority)
Dim frame As New DispatcherFrame()
Dim dispatcherOperation As DispatcherOperation = Dispatcher.CurrentDispatcher.BeginInvoke(priority, New DispatcherOperationCallback(ExitFrameOperation), frame)
Dispatcher.PushFrame(frame)
If dispatcherOperation.Status <> DispatcherOperationStatus.Completed Then
dispatcherOperation.Abort()
End If
End Sub
Private Shared Function ExitFrameOperation(obj As Object) As Object
(DirectCast(obj, DispatcherFrame)).[Continue] = False
Return Nothing
End Functionhttps://stackoverflow.com/questions/2667370
复制相似问题