C#如何做一个后台线程告诉UI线程,它已经完成了做什么? [英] C# How does a background thread tell a UI thread that it has finished doing something?

查看:220
本文介绍了C#如何做一个后台线程告诉UI线程,它已经完成了做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个C#的WinForms应用程序,做一些数据的处理。
你必须从一个由该UI线程调用数据库中检索数据的方法。
后台线程然后跑去做这个任务。
你想要的UI来继续做它的事,而不是被锁定了,没有响应。

Lets say you have a C# WinForms application that doing some data processing. You have a method that retrieves data from a database that is called by the UI thread. The background thread then runs off to do this task. You want the UI to carry on doing its thing and not be locked up and unresponsive.

你怎么让后台线程中运行了,并做了处理,然后自动提醒UI线程当它返回的结果?

How do you let the background thread run off and do its processing and then automatically alert the UI thread when it has returned the results?

推荐答案

如果你不使用后台工作线程(无论出于何种原因),那么你必须从火你的线程这是由UI线程处理的事件。例如,我有这样的代码,它可以扫描我的MP3和火灾事件发现每张专辑,然后当它完成了另一个事件(或停止):

If you don't use a background worker thread (for whatever reason) then you must fire an event from your thread which is handled by the UI thread. For example I have this code that scans my mp3s and fires and event for each album found and then another event when it finished (or is stopped):

    public void Build()
    {
        FindAlbums(Root);

        // Final update
        if (Library_Finished != null)
        {
            Library_Finished(this, null);
        }
    }

    private void FindAlbums(string root)
    {
        // Find all the albums
        string[] folders = Directory.GetDirectories(root);
        foreach (string folder in folders)
        {
            string[] files = Directory.GetFiles(folder, "*.mp3");
            if (files.Length > 0)
            {
                // Add to library - use first file as being representative of the whole album
                var info = new AlbumInfo(files[0]);
                if (Library_AlbumAdded != null)
                {
                    Library_AlbumAdded(this, new AlbumInfoEventArgs(info));
                }
            }

            FindAlbums(folder);
        }
    }



然后在UI线程(这是的WinForms代码)

Then in the UI thread (this is WinForms code):

    private void Library_AlbumAdded(object sender, AlbumInfoEventArgs e)
    {
        if (dataGridView.InvokeRequired)
        {
            dataGridView.Invoke((MethodInvoker)delegate { AddToGrid(e.AlbumInfo); });
        }
        else
        {
            AddToGrid(e.AlbumInfo);
        }
    }

    private void Library_Finished(object sender, EventArgs e)
    {
        if (dataGridView.InvokeRequired)
        {
            dataGridView.Invoke((MethodInvoker)delegate { FinalUpdate(); });
        }
        else
        {
            FinalUpdate();
        }
    }



我想,不过,建议您调查背景工作线程,因为它这么大管家给你的。然而,将需要相同的处理代码中的 RunWorkerCompleted 事件来更新UI。

这篇关于C#如何做一个后台线程告诉UI线程,它已经完成了做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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