如何使用后台工作程序进行多线程文本搜索并在c#中的列表视图中显示整行

时间:2018-03-16 07:24:34

标签: c# multithreading backgroundworker

所以,我有一个win表单,我必须在文本文件中搜索一个字符串,如果找到字符串,则显示行号和整行。搜索必须是多线程的,并且所有行号和行必须在列表视图上。例如,如果单词"语言"在行号60中,列表视图必须显示:

60"该行有单词language"

我在这方面使用了后台工作者,但我无法显示正确的行号和行。首先,一行显示多次,其次,行号始终为0.但是,当我在Console中输出结果时,结果是正确的。我想在将结果放入listview时会出错。 这里'我的主要形式.c

                      public partial class Form1 : Form
          {
             public Form1()
    {
        InitializeComponent();
    }

  //  private bool start_cancel;

    bool bln = true;

    private void StartCancelbtn_Click(object sender, EventArgs e)
    {
        if (bln)
            text2();
        else
            text1();

        bln = !bln;
    }


    private void text1()
    {
        StartCancelbtn.Text = "Start";
        this.backgroundWorker1.CancelAsync();


    }

    private void text2()
    {

        StartCancelbtn.Text = "Cancel";
        StartThread();
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        System.ComponentModel.BackgroundWorker worker;
        worker = (System.ComponentModel.BackgroundWorker)sender;

        // Get the Words object and call the main method.  
        main_work WC = (main_work)e.Argument;
        WC.CountWords(worker, e);
        if (worker.CancellationPending)
        {
            e.Cancel = true;
           // break;
        }
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        main_work.ReportState state =
   (main_work.ReportState)e.UserState;
        ListViewItem l1 = new ListViewItem();
                 l1.Text = state.LinesCounted.ToString();
        l1.SubItems.Add(state.line);
                   listView1.Items.Add(l1);
      }

      private void backgroundWorker1_RunWorkerCompleted(object sender,     

      RunWorkerCompletedEventArgs e)
       {
        if (e.Error != null)
            MessageBox.Show("Error: " + e.Error.Message);
        else if (e.Cancelled)
            MessageBox.Show("Word counting canceled.");
        else
            MessageBox.Show("Finished counting words.");

    }

    private void StartThread()
    {
        main_work WC  = new main_work();
        WC.CompareString = this.searchtext.Text;
        WC.SourceFile = this.filenametextbox.Text;

        // Start the asynchronous operation.  
        backgroundWorker1.RunWorkerAsync(WC);

    }

    private void browsebtn_Click(object sender, EventArgs e)
    {
        using (OpenFileDialog brw = new OpenFileDialog())
        {
            if (brw.ShowDialog() == DialogResult.OK)
            {
                using (StreamReader sr = new StreamReader(brw.FileName))
                {
                    filenametextbox.Text = brw.FileName.ToString();
                }
            }
        }
    }
        }
    }

这是我的main_work课程,其中进行了实际的比较:

       class main_work
       {
    public class ReportState

    {
       public int LinesCounted;
      public  string line;
    }
    Queue q = new Queue();
    public string SourceFile;
    public string CompareString;
    public string line2 ;
    public int linenumber=0;
    public int linenumber1 = 0;

    int LinesCounted1;
    //      public string line2;

    public void CountWords(
        System.ComponentModel.BackgroundWorker worker,
        System.ComponentModel.DoWorkEventArgs e)
    {
        // Initialize the variables.  
        ReportState state = new ReportState();
        string line1 = "";
        int elapsedTime = 1;
        DateTime lastReportDateTime = DateTime.Now;

        if (CompareString == null ||
            CompareString == System.String.Empty)
        {
            MessageBox.Show("Please Enter a string to be searched");
        }

        else
        {
            // Open a new stream.  
            using (System.IO.StreamReader myStream = new    System.IO.StreamReader(SourceFile))
            {
                // Process lines while there are lines remaining in the file.  
                while (!myStream.EndOfStream)
                {
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        // break;
                    }
                    else
                    {
                        line1 = myStream.ReadLine();
                        line2 = (CountInString(line1, CompareString));
                        LinesCounted1 = (linenumbercount(line1, CompareString, linenumber1));

                                              //    Raise an event so the form can monitor progress.
                        int compare = DateTime.Compare(
                        DateTime.Now, lastReportDateTime.AddSeconds(elapsedTime));
                        if (compare > 0)
                        {
                            state.LinesCounted = LinesCounted1;
                            state.line = line2;
                            worker.ReportProgress(0, state);
                            lastReportDateTime = DateTime.Now;
                        }

                        System.Threading.Thread.Sleep(1);

                    }
                }

                // Report the final count values.
                   state.LinesCounted = LinesCounted1;
                 state.line = line1;
                worker.ReportProgress(0, state);
                lastReportDateTime = DateTime.Now;

            }
        }
    }
    private string CountInString(
   string SourceString,
   string CompareString)
    {

                  if (SourceString.Contains(CompareString))
        {
                             line2 = SourceString;
            Console.WriteLine(SourceString);

        }
        return line2;


    }

    private int linenumbercount(
   string SourceString,
   string CompareString,
   int linenumber)
    {
       // Lines = 0;
        if (SourceString == null)
        {
            return 0;
        }
        if (SourceString.Contains(CompareString))
        {
                           Console.WriteLine(linenumber);

        }

         linenumber++;
           return linenumber;



              }
            }

任何反馈都会有所帮助。请让我知道我做错了什么,我犯了什么错误,因为我是背景工作者和多线程的新手。感谢。

0 个答案:

没有答案