C# 检查listbox.SelectedIndex==listbox.Items.Count是否来自BackgroundWorker

C# 检查listbox.SelectedIndex==listbox.Items.Count是否来自BackgroundWorker,c#,multithreading,listbox,C#,Multithreading,Listbox,我必须检查列表框的SelectedIndex是否位于BackgroundWorker的最后一个索引处,但由于我正在从BackgroundWorker检查列表框(在GUI线程上),我得到以下错误: System.InvalidOperationException:'跨线程操作无效:从创建控件的线程以外的线程访问控件'listBox1' 这是我的代码: if (listBox1.SelectedIndex == listBox1.Items.Count) { //code here } 如果不在G

我必须检查列表框的
SelectedIndex
是否位于
BackgroundWorker
的最后一个索引处,但由于我正在从
BackgroundWorker
检查列表框(在GUI线程上),我得到以下错误:

System.InvalidOperationException:'跨线程操作无效:从创建控件的线程以外的线程访问控件'listBox1'

这是我的代码:

if (listBox1.SelectedIndex == listBox1.Items.Count)
{
//code here
}

如果不在GUI线程上,我如何使if语句工作?

这基本上是在从另一个线程访问forms属性时发生的,这就是引发此异常的原因。您的UI操作必须在所属线程上执行

您可以这样做:

 int intIndex = 0;
 int intCount = 0;
        if (listBox1.InvokeRequired)
        {
            listBox1.Invoke(new MethodInvoker(delegate { intIndex = listBox1.SelectedIndex ; }));
        }

        if (listBox1.InvokeRequired)
        {
            listBox1.Invoke(new MethodInvoker(delegate { intCount = listBox1.Items.Count; }));
        }
那么你的情况是:

        if (intIndex == intCount)
        {
            // TODO: Business Logic
        }
或者你可以做这个快速修复,但不建议在生产上做,但你可以在开发上做。您可以将其添加到构造函数窗体中:

CheckForIllegalCrossThreadCalls = false;

不可以。决不能将
CheckForIllegalCrossThreadCalls
设置为
false
。所有这些都会延迟发现使用错误线程的控件不可避免地会导致的问题。谢谢,这正是我想要的。等我回家后再测试!好的,让我知道它是否有效,如果这回答了你的问题,你可以接受它作为答案,谢谢@ThomasIt工作得很好,但不知道如何将其标记为手机上的答案。