c# 如何处理ListView foreach 块程序? [英] c# How to deal with ListView foreach block program?

查看:32
本文介绍了c# 如何处理ListView foreach 块程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

c# 如何处理ListView Threading foreach 程序?我尝试更新签入列表,如果我不使用 Task.Run(Threading),它会阻塞程序.如果我使用 Task.Run,​​它会导致 InvalidOperationException

c# How to deal with ListView Threading foreach program? I try to update the Checked in List, If I don't use Task.Run(Threading), it will block the program. If I use Task.Run, It will cause the InvalidOperationException

Task.Run(() =>
            {
                // Cause System.InvalidOperationException
                foreach (ListViewItem item in liv.Items) 
                {
                    var fullPath = item.SubItems["fullPath"].Text;
                    
                    foreach (var gl in geminiFileStructListForLV)
                    {
                        if (fullPath.Equals(gl.fullPath))
                        {
                            gl.Checked = item.Checked;
                        }
                    }
                }
            });

推荐答案

首先,gl.Checked = item.Checked; 是不允许的.因为您不能修改 foreach 迭代变量 的成员.您必须将 foreach 更改为 for

Firstly, gl.Checked = item.Checked; is not permitted. Because you cannot modify members of a foreach iteration variable. You have to change your foreach to for

其次,跨线程操作对控件无效.这只是意味着您不能使用由另一个线程内的主线程创建的 Control

Secondly, Cross-Thread operations are not valid for Controls. It simply means you can't use a Control which was created by the Main thread inside another thread

避免循环阻塞程序的最简单方法是调用 Application.DoEvents(); 在循环的每个循环中:

The most simple way to avoid blocking the program by the loops is to call Application.DoEvents(); in every cycle of your loop:

foreach(ListViewItem item in liv.Items)
{
    var fullPath = item.SubItems["fullPath"].Text;

    for(var i = 0; i < geminiFileStructListForLV.Length; i++)
    {
        if(fullPath.Equals(geminiFileStructListForLV[i].fullPath))
        {
            geminiFileStructListForLV[i].Checked = item.Checked;
        }

        Application.DoEvents();
    }
}

这篇关于c# 如何处理ListView foreach 块程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆