gpt4 book ai didi

c# - C#中使用Threads和ListView的问题

转载 作者:行者123 更新时间:2023-12-04 00:24:07 25 4
gpt4 key购买 nike

我有一个文本过滤器,在 TextChanged 事件中我以这种方式启动 ListView 填充代码:

ThreadPool.QueueUserWorkItem(new WaitCallback(populate));

然后在填充方法中我有这样的代码

listView1.BeginUpdate();
listView1.Clear();

// rest of the code

listView1.EndUpdate();

但是 listView1.BeginUpdate() 调用给出以下异常:

System.NotSupportedException was unhandled
Message="An error message cannot be displayed because an optional resource assembly containing it cannot be found"
StackTrace:
at Microsoft.AGL.Common.MISC.HandleAr()
at System.Windows.Forms.ListView.ntvSetStyleEx()
at System.Windows.Forms.ListView.BeginUpdate()
at App.frmSelectClient.populate()
at WorkItem.doWork()
at System.Threading.Timer.ring()
InnerException:

我做错了什么?

我想在后台线程中发出 ListView 的填充。

最佳答案

您无法从 UI 线程以外的任何线程更新 UI 元素。使用 Control.Invoke/BeginInvoke 来执行此操作。

您可以在后台线程中执行所有数据加载等操作,但您需要编码到 UI 线程以实际填充 UI 控件本身。

大多数 UI 框架都是这种情况 - 当然还有 Windows 窗体(桌面和 CF)和 Windows Presentation Foundation(在其中使用 Dispatcher 而不是 Control.Invoke/BeginInvoke)。

需要注意的一点:如果我没记错的话,Compact Framework 仅支持 Control.Invoke/BeginInvoke 的 EventHandler 委托(delegate)。诚然,这可能在最近的版本中发生了变化。

关于c# - C#中使用Threads和ListView的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2302982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com