VB.NET中Invoke调用无法返回正确值问题排查
问题原因与解决方案
你的问题出在委托类型不匹配:原方法是带返回值的Function,但调用Invoke时用了无返回值的Action(Of String)委托,导致Invoke无法正确传递方法的返回结果,最终得到Nothing。
修正后的代码如下:
Public Function listview1FindItemWithText(ByVal value As String) As ListViewItem If InvokeRequired Then ' 替换为带返回值的Func委托,而非无返回值的Action Return CType(Me.Invoke(New Func(Of String, ListViewItem)(AddressOf listview1FindItemWithText), value), ListViewItem) End If Return ListView1.FindItemWithText(value) End Function
关键说明
Action(Of String)是无返回值委托,无法承载原方法的返回结果;改用Func(Of String, ListViewItem)(输入为String、返回值为ListViewItem的委托)后,才能正确传递返回值。- 必须保证Invoke使用的委托类型与目标方法的输入、输出完全匹配,才能让跨线程调用返回预期结果。
内容的提问来源于stack exchange,提问作者Michal Bogs
相关产品推荐
相关产品推荐

