有没有人有一个简单的方法来使这个TreeView WinForm应用程序多线程 - UI锁定。 [英] Does anyone have a simple way of making this TreeView WinForm app multithreaded – the UI locks up.

查看:54
本文介绍了有没有人有一个简单的方法来使这个TreeView WinForm应用程序多线程 - UI锁定。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人有一个简单的方法让这个TreeView WinForm应用程序多线程 - UI锁定。我已经尝试了backgroundworker,treeview.invoke和代表,但在这些方面需要帮助。提前感谢你的帮助。

Does anyone have a simple way of making this TreeView WinForm app multithreaded – the UI locks up. I have experimented with the backgroundworker , treeview.invoke and delegates but need help in these areas. Thank you in advance for any assistance.

推荐答案

做线程的东西很简单 - 后台工作人员会处理:

Doing the Threading stuff is pretty easy - a Background worker will handle that:
    BackgroundWorker work = new BackgroundWorker();
    work.DoWork += new DoWorkEventHandler(work_DoWork);
    work.ProgressChanged += new ProgressChangedEventHandler(work_ProgressChanged);
    work.WorkerReportsProgress = true;
    work.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerCompleted);
    work.RunWorkerAsync(files);
    ...

void work_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
    butSync.Enabled = true;
    }

void work_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
    string mess = e.UserState as string;//string.Format("{0}/{1}: {2}", e.ProgressPercentage, files.Length, files[e.ProgressPercentage]);
    Console.WriteLine(mess);
    }

void work_DoWork(object sender, DoWorkEventArgs e)
    {
    BackgroundWorker work = sender as BackgroundWorker;
    // Do background loop here.
    }

当您添加实际的TreeNodes时会出现复杂问题,因为后台工作程序无法直接访问UI组件(例如TreeView)而不会导致交叉线程异常。你可以使用Invoke将代码移动到你的主线程上,但是你会在像这样的应用程序中像一个懒人一样抛出事件。



我使用的方法上次我这样做是为了在后台工作器中创建文件夹作为列表,然后使用Worker.ReportProgess将列表及其应用的节点传递回UI线程以供其添加 - 因为每个事件都是一组有限的工作,它不会对用户界面产生如此糟糕的影响,用户每次都会得到明智的更新。

The complication comes when you are adding the actual TreeNodes, because the background worker can't access UI components (such as the TreeView) directly without causing a cross threading exception. You could use Invoke to move that code onto your main thread, but then you are throwing events around like a loon in an application such as this.

The method I used last time I did this was to create the folders as a list in the background worker and then use the Worker.ReportProgess to pass the list and the node to which it applies back up to the UI thread for it to add - because each event does a limited set of work it doesn't impact the UI so badly and the user gets a sensible update each time.


这篇关于有没有人有一个简单的方法来使这个TreeView WinForm应用程序多线程 - UI锁定。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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