在BackgroundWorker中运行类方法时,如何以不同的形式重用类?

时间:2012-05-03 18:30:20

标签: c# backgroundworker

我在Form1中有这个功能,这个功能很好,我的想法就是从一个大的xml文件中检索一些文本。所以在Form1构造中我做了:

r = new StreamReader(@"D:\Deponia_Work\Deponia Extracted Files\000004aa.xml");
f = r.ReadToEnd();
r.Close();

变量f是字符串。

现在我在Form1中使用了这个函数,我称之为test(),它正在从大000004aa.xml文件中查找/提取文本。

private void test()
        {
            int countFiles = 0;
            byte[] a;
            string startTag = "T256=\"";
            string endTag = "\"";
            int index = 0;
            int startTagWidth = startTag.Length;
            int endTagWidth = endTag.Length;
            int fileLength = f.Length;
            w = new StreamWriter(@"d:\testingdeponias.txt");
            while (true)
            {
                if (index > f.LastIndexOf(startTag))
                {
                    break;
                }
                int startTagIndex = f.IndexOf(startTag, index);
                int stringIndex = startTagIndex + startTagWidth;
                index = stringIndex;

                int endTagIndex = f.IndexOf(endTag, index);
                int stringLength = endTagIndex - stringIndex;
                if (stringLength == 0)
                {
                }
                else
                {
                    string test = f.Substring(stringIndex, stringLength);
                    if (test.Contains("<pa>"))
                    {
                        string t = "<pa>";
                        int y = t.Length;
                        string test1 = test.Substring(0, stringLength - y);
                        listBox1.Items.Add(test1);
                        w.WriteLine(test1);
                    }
                    //else
                    // {
                    listBox1.Items.Add(test);
                    w.WriteLine(test);
                    // }
                }
            }
            w.Close();
        }

然后我向Form1添加了一个新的backgroudnworker2事件:

这是DoWork活动:

private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker2 = sender as BackgroundWorker;
            lists1.extractTextDeponia(worker2, backgroundWorker2, listBox1, textBox1,f, w, e);
        }

这是我启动backgroundworker的按钮点击事件:

private void button8_Click(object sender, EventArgs e)
        {
            backgroundWorker2.RunWorkerAsync();
        }

在新类中,我创建了一个新的函数公共函数,它从Form1中获取一些变量。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Web;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;

namespace List_Words
{
    class Lists
    {

        public void List_Words()
        {

        }

        public void extractTextDeponia(BackgroundWorker worker, BackgroundWorker backgroundWorker2, ListBox lbox , TextBox tbox , StreamWriter streamW , string read, DoWorkEventArgs e)
        {

我的问题是如何更改并将test()函数从Form1转换为新类到新函数中,以便它也可以与backgroundworker2一起使用?

我试图在那里使用/添加FileStream并添加了一个循环读取的循环,但它没有用。

**这是具有函数的新类,因为它是Form1中的test()**

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Web;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;

namespace List_Words
{
    class Lists
    {

        public void List_Words()
        {

        }

        public void extractTextDeponia(BackgroundWorker worker, BackgroundWorker backgroundWorker2, ListBox lbox , TextBox tbox , StreamWriter streamW , string read, DoWorkEventArgs e)
        {
            string startTag = "T256=\"";
            string endTag = "\"";
            int index = 0;
            int startTagWidth = startTag.Length;
            int endTagWidth = endTag.Length;
            int fileLength = read.Length;
            using (var fs = new FileStream(@"D:\Deponia_Work\Deponia Extracted Files\000004aa.xml", FileMode.Open, FileAccess.Read))
            {

                using (var h = new StreamReader(fs))
                {
                    string line;
                    line = h.ReadLine();
                    while ((line = h.ReadLine()) != null)
                    {
                        if (worker.CancellationPending == true)
                        {
                            e.Cancel = true;
                            break;
                        }
                        else
                        {
                            int percent = (int)(fs.Position * 100 / fs.Length);
                            backgroundWorker2.ReportProgress(percent);
                            if (index > read.LastIndexOf(startTag))
                            {
                                break;
                            }
                            int startTagIndex = read.IndexOf(startTag, index);
                            int stringIndex = startTagIndex + startTagWidth;
                            index = stringIndex;

                            int endTagIndex = read.IndexOf(endTag, index);
                            int stringLength = endTagIndex - stringIndex;
                            if (stringLength == 0)
                            {
                            }
                            else
                            {
                                line = read.Substring(stringIndex, stringLength);
                                if (line.Contains("<pa>"))
                                {
                                    string t = "<pa>";
                                    int y = t.Length;
                                    string test1 = line.Substring(0, stringLength - y);
                                    if (lbox.InvokeRequired)
                                    {
                                        lbox.Invoke(new MethodInvoker(delegate { lbox.Items.Add(test1); }));
                                    }
                                    //w.WriteLine(test1);
                                    line = h.ReadLine();
                                    if (tbox.InvokeRequired)
                                    {
                                        tbox.Invoke(new MethodInvoker(delegate { tbox.Text = test1; }));
                                    }
                                }
                                //else
                                // {
                                if (lbox.InvokeRequired)
                                {
                                    lbox.Invoke(new MethodInvoker(delegate { lbox.Items.Add(line); }));
                                }
                                //w.WriteLine(line);
                                if (tbox.InvokeRequired)
                                {
                                    tbox.Invoke(new MethodInvoker(delegate { tbox.Text = line; }));
                                }
                                // }
                            }
                        }
                    }
                }
            }
            streamW = new StreamWriter(@"d:\testingdeponias.txt");
            streamW.AutoFlush = true;
            streamW.Write(read);
            streamW.Close();
        }


    }
}

在form1中我称之为:

BackgroundWorker worker2 = sender as BackgroundWorker;
lists1.extractTextDeponia(worker2, backgroundWorker2, listBox1, textBox1,w, f, e);

w是流编写器f是字符串,e是backgroundowrker2 DoWork e变量 正如我在上面展示的那样,我在Form1构造函数中使用f来读取大的xml文件,但我也在新的类和函数中使用FileStream做了一件乱七八糟的事情。 **

1 个答案:

答案 0 :(得分:0)

可能有所帮助的一点是改变你的编程思维方式。考虑对这些数据实体的数据实体和操作,而不是考虑表单和事件,您可以使用服务类型模式。

所以你要做的就是创建一个服务类,它会做你想做的事情。由于您正在使用后台工作程序,因此我将其创建为实例类而不是静态类。

public class FileWorkerService
{
   private BackgroundWorker _worker;

   public FileWorkerService()
    {
       _worker = new BackgroundWorker();
    }

   public void ReadFileAndProcessIt()
    {
      if (!_worker.IsBusy)
        {
          _worker.RunWorkerAsync();
        }
    } 
 }

现在,只需按照之前的事件连接_worker,您的服务类就可以开始工作了。

为了让它做某事,你只需创建一个实例并调用启动worker的函数。

所以在你的表单按钮上点击你会...

private void button8_Click(object sender, EventArgs e)
        {
            var newService = new FileWorkerService();
            newService.ReadFileAndProcessIt();
        }
  
    
      

=================编辑============================= =====        - 添加了如何从服务中更新后台工作程序的进度。       <<< ================================================== ======

    
  

在FileWorkerService类中

public void SetWorkerProgress(int currentValue)
{
   _worker.ReportProgress(currentValue);
}

要在课堂外打电话,你可以从主表格开始......

newService.SetWorkerProgress(whatever);