【问题标题】:Getting a listbox item value safely in a thread在线程中安全地获取列表框项值
【发布时间】:2013-04-29 05:00:59
【问题描述】:

您好,我有一个运行线程并在进程中更新 UI 的程序。我已将 .invokerequired 用于安全线程,并且一切运行正常。在其中一个线程中,有必要使用在另一个线程(ListBox2.Items(index)) 中创建的列表框中的项目的值,而我目前正在使用dim item1 as integer =ListBox2.Items(index) 执行此操作。现在程序运行良好并且没有显示异常或错误消息,但是,如果我添加同一行的手表,我会收到以下消息 + AccessibilityObject {"Cross-thread operation not valid: Control 'ListBox2' access from a thread other比创建它的线程。"} System.InvalidOperationException.

正常吗?有没有办法安全地获取列表框中位于另一个线程上的项目的值?

【问题讨论】:

  • 使用委托,或者只使用后台工作人员。
  • 您可以在这里查看更多信息:stackoverflow.com/questions/3969476/…
  • 我无法使用委托来获取 (ListBox2.Items(index)) 的值。我不需要对 UI 进行任何更改,我只想以线程安全的方式获取 ListBox2.Items(index) 的值。
  • 不要在线程中创建ui元素,使用control.invoke在ui线程上创建和访问。

标签: vb.net invoke


【解决方案1】:

要回答有关跨线程异常的问题,这是正常的,您不能从与创建它们的线程不同的线程访问 ui 元素。要解决此问题,您需要使用 control.invoke() 执行 lambda 表达式以在创建列表框的线程上运行访问代码。

Dim item1 as Integer
If ListBox2.InvokeRequired then
    Listbox2.Invoke(Sub() Item1 = ListBox2.Items(Index))
Else
    Item1 = ListBox2.Items(Index)
End If

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2023-03-15
    相关资源
    最近更新 更多