其他分享
首页 > 其他分享> > CodeGo.net>在对象中使用BackgroundWorker并更新UI

CodeGo.net>在对象中使用BackgroundWorker并更新UI

作者:互联网

编辑:希望到某个地方

这是我所拥有的,但是我不确定如何将bcLoad.ReportProgress(i)委派给创建的对象(即如何进行委派以便可以传递).我已经创建了可以工作的对象事件(可以调用我的对象方法,并且可以看到在线阅读时触发的更改).我知道objectChanged何时工作(写入控制台).但是,bcLoad_RunWorkerCompleted似乎不起作用,if语句中的代码从未执行过,所以我在某个地方出错了.该文件虽然加载.

有人可以阐明如何创建委托,然后在哪部分使用传递委托(我在对象中假设),以及为什么bcLoad_RunWorkerComplete为null.
这确实是我第一次在C#中使用事件,委托和背景工作人员

/*
The object which does file operations
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Collections;
using System.Windows.Forms;
using System.ComponentModel;
using System.Data;

namespace aodProductionViewer
{
    public class fileOperationsSpecial
    {
        public event EventHandler Changed;

        protected virtual void OnChanged(EventArgs e)
        {
            if (Changed != null)
            {
                Changed(this, e);
            }
        }

        public fileOperationsSpecial() 
        {        }

        /// <summary>
        /// Count the number of lines in the file specified.
        /// </summary>
        /// <param name="f">The filename to count lines in.</param>
        /// <returns>The number of lines in the file.</returns>
        static long CountLinesInFile(string f)
        {
            long count = 0;
            try
            {
                using (StreamReader r = new StreamReader(f))
                {
                    string line;
                    while ((line = r.ReadLine()) != null)
                    {
                        count++;
                    }
                }
            }
            catch (Exception err)
            {
                string strTemp = "Error get number of lines for save game file. \n" +
                                err.ToString();
                errorDialog errDiag = new errorDialog("save game line count",
                                        strTemp, true);
            }
            return count;
        }

        /// <summary>
        /// Use this to readin in a file
        /// </summary>
        /// <param name="strPath">Path of file to read in</param>
        /// <returns>a string array of the file</returns>
        public string[] readFile(string strPath)
        {
            long lng_LineCount = CountLinesInFile(strPath);
            string[] strReadIn = new string[lng_LineCount];
            try
            {
                long lngCount = 0;
                using (StreamReader reader = new StreamReader(strPath))
                {
                    String line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        strReadIn[lngCount] = line;
                        lngCount++;
                        OnChanged(EventArgs.Empty);
                    }
                }

            }
            catch (Exception err)
            { //            
            }

            return strReadIn;
        }
   }
}

/*
Event Listner
*/
using System;
using System.Collections.Generic;
using System.Text;

namespace aodProductionViewer
{
    class EventListener
    {
        private fileOperationsSpecial FPS;

        public EventListener(fileOperationsSpecial _fps)
        {
            FPS = _fps;
            FPS.Changed += new EventHandler(objectChanged);
        }

        private void objectChanged(object sender, EventArgs e)
        {            //changed has occured
        }

        public void Detach()
        {
            FPS.Changed -= new EventHandler(objectChanged);
            FPS = null;
        }
    }
}

/*
The backgroundWorker code (Part of)
*/

    BackgroundWorker bcLoad = new BackgroundWorker();

    private void btt_load_save_game_Click(object sender, EventArgs e)
    {
        //Do some file dialog stuff
        string strPath = null;
        bcLoad.RunWorkerAsync(strPath);
    }

    void bcLoad_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        tb_ProgressBar.Value = e.ProgressPercentage;
    }

    void bcLoad_DoWork(object sender, DoWorkEventArgs e)
    {
        string strPath = e.Argument as string;
        fileOperationsSpecial FPS = new fileOperationsSpecial();
        EventListener listener = new EventListener(FPS);
        string strArray = FPS.readFile(strPath);
        listener.Detach();
    }

    void bcLoad_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (e.Result != null)
        {
            //Everything done
            tb_ProgressBar.Visible = false;
        }
    }

我的主旨是使用BackgroundWorker进行一些工作并更新UI以进行进度和完成,此刻我已经有了一些简单的方法,如您所见,我传递了一个字符串(这是一条路径),然后读取文件并更新进度,目前,我只是在休眠线程并为演示目的设置进度.我也打算返回一个对象(字符串数组),但是我还没有解决这个问题.

现在我的问题是,如何在我的表单创建的对象中执行所有这些操作并仍然更新UI?我有一个当前对文件进行操作的对象(即读取文件,写入,获取信息).

目前,按照我的理解,下面的演示正在进行
表格>后台工作人员>更新表单以获取进度.

我想去

表格>创建对象>后台工作人员>更新进度表>返回字符串数组

我已经看过了,并且没有在任何示例中做任何事情,所以我想问问那些会知道的人.这有可能吗?我试图针对的是从表单中删除所有文件处理,以便于管理和维护.

有关如何执行此操作的完整代码示例将非常棒!

这是到目前为止我所了解的(请记住,仅出于示例目的,它将无法编译)

BackgroundWorker bcLoad = new BackgroundWorker();

    public frm_ProductionViewer()
    {
        InitializeComponent();
        load_settings();
        bcLoad.DoWork += new DoWorkEventHandler(bcLoad_DoWork);
        bcLoad.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bcLoad_RunWorkerCompleted);

        bcLoad.WorkerReportsProgress = true;
        bcLoad.ProgressChanged += new ProgressChangedEventHandler(bcLoad_ProgressChanged);

        bcLoad.WorkerSupportsCancellation = true;
    }

private void btt_load_save_game_Click(object sender, EventArgs e)
    {

        ts_label_GameLoaded.Text = "Loading";
        bcLoad.RunWorkerAsync(strPath);
    }

void bcLoad_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        tb_ProgressBar.Value = e.ProgressPercentage;
    }

    void bcLoad_DoWork(object sender, DoWorkEventArgs e)
    {
            string strPath = e.Argument as string;
            //load file
            //Update progress
            bcLoad.ReportProgress(80);
            Thread.Sleep(300 * 5);
            bcLoad.ReportProgress(100);
    }

    void bcLoad_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (e.Result != null)
        {
            textBox1.Text = "done";
        }
        tb_ProgressBar.Visible = false; ;
        ts_label_GameLoaded.Text = "Loaded";
    }

解决方法:

您的对象(可处理文件)最好不依赖于GUI或Bgw.

因此,保持您的Bgw与(在表单上)并调用对象表单DoWork.

要报告反馈,您的Object需要一个事件(或使用委托参数的主要方法).

在该事件的处理程序中(在工作线程上调用),调用bcLoad.ReportProgress(percent).

对编辑的反应:

>您需要一个带有百分比空间的EventArgs类型,例如EventHandler< ProgressEventArgs> ,您可能必须编写ProgressEventArgs.
>我认为您不需要单独的EventListener类.这是表格工作.那会让你:

class Form ...
{
    private void objectChanged(object sender, ProgressEventArgs e)
    {   //changed has occured
        // trigger the Bgw event
        // or use Form.Invoke here to set the progress directly
        bcLoad.ReportProgress(e.Percentage);          
    }

}

因此,“更改”现在通过2个事件处理程序进行过滤. 1打破FPS的依赖性,1同步到Form.

标签:multithreading,backgroundworker,c,user-interface,winforms
来源: https://codeday.me/bug/20191209/2097513.html