调用函数的线程问题 [英] Threading problem with calling a function

查看:61
本文介绍了调用函数的线程问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我编写了一个应用程序,该程序可搜索硬盘中的文件,但是这部分代码没有任何错误消息或...不起作用.
代码:

Hi,
I''ve written an app that searches for files in hard disk , but this part of code without any error message or ... doesn''t work.
code:

private void Go_Click(object sender, EventArgs e)
        {
            drives = System.Environment.GetLogicalDrives();
            Thread t = new Thread(() => Engine(drives));
            t.Start();
        }
        private void Engine(string[] path)
        {
            foreach (string s in path)
            {
                try
                {
                    foreach (string f in System.IO.Directory.GetFiles(s))
                        list.Items.Add(f);
                    Engine(System.IO.Directory.GetDirectories(s));
                }
                catch { continue; }
            }
        }


谁能告诉我为什么它不起作用?!
谢谢.


can anyone tell me why it doesn''t work?!
Thanks.

推荐答案

您不能从线程更改UI控件(作为ListView).您必须执行 Control.Invoke [如何:从线程操纵控件 [ ^ ]
You cannot change UI controls (as ListView) from the thread. You have to do a Control.Invoke[^].

See How to: Manipulate Controls from Threads[^]


您正在使用异常,这是编写catch块的最差方法.将一些代码放在catch块中以显示/记录错误消息,您将知道代码为什么失败.
You are consuming your exception, that''s the worst way to write a catch block. Put some code in your catch block to display/log your error message and you''ll know why your code fails.


我猜列表是一个控件吗?如果是这样,那就是您的问题.您正在对Windows控件进行跨线程访问.那是不对的.您需要执行该list.Items.Add部分回到您的GUI线程上.
如何执行此操作取决于您使用的是WPF还是Windows窗体.对于WPF,请使用Dispatcher.Invoke或Dispatcher.BeginInvoke.对于表单,请使用Control.Invoke或Control.BeginInvoke.
I''m guessing list is a control? If so, that''s your problem. You are making a cross thread access to a Windows control. That is a no-no. You need to do that list.Items.Add part back on your GUI thread.
How you do that depends on if you are using WPF or Windows forms. For WPF you use Dispatcher.Invoke or Dispatcher.BeginInvoke. For forms you use Control.Invoke or Control.BeginInvoke.


这篇关于调用函数的线程问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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