为什么这样:
Private [Function] As Func(Of Double, String) = Function(ByRef z As Double) z.ToString
Run Code Online (Sandbox Code Playgroud)
给出以下错误:
嵌套函数没有与委托String)兼容的签名.
这个:
Private [Function] As Func(Of Double, String) = Function(ByVal z As Double) z.ToString
Run Code Online (Sandbox Code Playgroud)
才不是?(区别是ByRef/ByVal)
而且,我怎么能实现这样的事情呢?
这是关于锁定两个List(Of T)对象的先前问题的后续行动.那里的答案很有帮助,但又给我留下了另一个问题.
假设我有这样的函数:
Public Function ListWork() As Integer
List1.Clear()
..Some other work which does not modify List1..
List1.AddRange(SomeArray)
..Some more work that does not involve List1..
Return List1.Count
End Function
Run Code Online (Sandbox Code Playgroud)
它驻留在声明List1的类中.在多线程环境中,我现在明白我应该为List1设置一个私有锁定对象,并在修改或枚举时锁定List1.我的问题是,我应该这样做:
Private List1Lock As New Object
Public Function ListWork() As Integer
SyncLock List1Lock
List1.Clear()
End SyncLock
..Some other work which does not modify List1..
SyncLock List1Lock
List1.AddRange(SomeArray)
End SyncLock
..Some more work that does not involve List1..
SyncLock List1Lock
Dim list1Count As Integer = List1.Count
End SyncLock
Return …Run Code Online (Sandbox Code Playgroud) VB.NET 2010,.NET 4
你好,
我最近读到了使用SynchronizationContext对象来控制某些代码的执行线程.我一直在使用通用子例程来处理(可能)跨线程调用,例如更新使用的UI控件Invoke.我是一名业余爱好者,很难理解任何特定方法的优缺点.我正在寻找一些有关哪种方法可能更可行以及为什么更有用的见解.
更新:此问题的部分原因在于MSDN页面中Control.InvokeRequired的以下语句.
更好的解决方案是使用
SynchronizationContext返回的SynchronizationContext而不是控件来进行跨线程编组.
而且,对于为什么,在我看来,大多数关于SO上此类问题的问题的答案的建议都提出了Invoke这种方法,并没有提到这种方法.
方法1:
Public Sub InvokeControl(Of T As Control)(ByVal Control As T, ByVal Action As Action(Of T))
If Control.InvokeRequired Then
Control.Invoke(New Action(Of T, Action(Of T))(AddressOf InvokeControl), New Object() {Control, Action})
Else
Action(Control)
End If
End Sub
Run Code Online (Sandbox Code Playgroud)
方法2:
Public Sub UIAction(Of T As Control)(ByVal Control As T, ByVal Action As Action(Of Control))
SyncContext.Send(New Threading.SendOrPostCallback(Sub() Action(Control)), Nothing)
End Sub
Run Code Online (Sandbox Code Playgroud)
在我的UI表单的构造函数中定义SyncContext的Threading.SynchronizationContext …
VB.NET 2010,.NET 4
大家好,
我的问题是,想象我有两个List(Of T)对象和多线程环境中的一个子程序,它修改了这两个对象.我不太了解锁,所以我不确定我是否可以这样做:
SyncLock CType(List1, IList).SyncRoot
List1.Clear()
List2.Clear()
End SyncLock
Run Code Online (Sandbox Code Playgroud)
或者我必须:
SyncLock CType(List1, IList).SyncRoot
SyncLock CType(List2, IList).SyncRoot
List1.Clear()
List2.Clear()
End SyncLock
End SyncLock
Run Code Online (Sandbox Code Playgroud)
?任何见解?我是否走在正确的轨道上?任何意见将不胜感激.
布莱恩,非常感谢