![](/img/trans.png)
[英]How to fill dataGrid view from backgroundWorker_DoWork Result
[英]Access of ImageList1 from Backgroundworker_DoWork without using any “delegate” with C#
我正在使用帶有Net 2的C#System Windows窗體(我只是一個初學者,所以請耐心等待),並想將Backgroundworker-Process中的圖像添加到Form1上的ImageList1中,以避免GUI凍結,而文件名圖標從較大包含10000多個文件的目錄在ListView中顯示,帶有文件名和圖標。
我存儲在列表中的文件名,並使用AddRange方法將其添加到Backgroundworker完成的事件中。 圖片無法以這種方式存儲,否則會失去質量。 我必須直接在DoWork()事件部分的Backgroundworker-Process中添加它們。 並存在一個問題:在我的免費版本的Microsoft Visual Studio 2008中,出現了一條長錯誤消息,其中大約有些奇怪: Cannot access ImageList1 because it was created in another thread...????
。
我打開了一張Microsoft票,他們回答我,這是免費版本的問題,一個錯誤。 是這樣還是可以幫助我。 我在Google中發現了有關“代理人”的一些信息,但恐怕我對使用這種構造一無所知。 我只知道如何聲明一個“ int”,一個字符串和一個列表,更多的不是,我可以在表單上放置一些用戶控件或在事件中填寫一些簡單的代碼。 也許你們中的某人有類似的問題,並且可以提出一個准確易用的易於使用的解決方案。 如何抑制有關ImageList中其他線程的錯誤? C#中可能存在諸如“ On Error Resume Next”之類的語句,該語句強制代碼繼續執行,無論如何。 然后,許多VB6應用程序將能夠再次在Sharp上運行,dunno ofc。 請幫忙。
這是一種方法:
ImageList1.Invoke(ActionNameHere)
替換已移至Action的代碼。 這是一個簡化的示例,代碼將從backgroundworker更新Label的Text屬性:
Action act = () =>
{
label1.Text = "Test updating UI property from background thread";
};
worker.DoWork += (o, args) =>
{
label1.Invoke(act);
};
worker.RunWorkerAsync();
您沒有發布代碼,因此我建議您使用以下代碼片段,它應該可以工作:
使用backgroundWorker時,使用@Keith 模板總是很方便
BackgroundWorker bw = new BackgroundWorker { WorkerReportsProgress = true };
bw.DoWork += (sender, e) =>
{
//what happens here must not touch the form
//as it's in a different thread
Action AccessImageList = () => { int count = imgLst.Images.Count;//access the image list };
this.Invoke(AccessImageList, new object[] { });
};
bw.ProgressChanged += ( sender, e ) =>
{
//update progress bars here
};
bw.RunWorkerCompleted += (sender, e) =>
{
//now you're back in the UI thread you can update the form
//remember to dispose of bw now
};
worker.RunWorkerAsync();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.