How does one write Subroutines within top level routines in C#?

I want to add a BackgroundWorker control to my code. So, I need my
bw_DoWork(object sender, DoWorkEventArgs e)
} <-- Line 57
} <-- Line 158
routine to be wrapped around other routines (between Code Lines 57 through 158), that I guess would then be called subroutines.
When I attempt this, I notice the word "void" in my other two routines (at the same level of the DoWork routine) have a squiggly line under them (i.e. my private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e) AND my "private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)" routines.
How do I need to write/structure this? Code below.
Many thanks,
Wallace
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
 
namespace ParseLogErrors
{
    public partial class Form1 : Form
    {
        private System.Collections.Specialized.StringCollection folderCol;
       
        public Form1()
        {
            InitializeComponent();
            this.labelFileCountDisplay.Text = "";
            //this.lvwFilesAndFolders.ItemActivate += System.EventHandler(this.lvwFilesAndFolders_ItemActivate);
        }
 
        private void buttonParseLogs_Click(object sender, EventArgs e)
        {
            string dirName = textBoxSearchPath.Text;
                        
            // Set current working directory & verify it exists
            if (Directory.Exists(dirName))
            try
            {
                Directory.SetCurrentDirectory(dirName);
                MessageBox.Show(dirName);
            }
            catch (UnauthorizedAccessException)
            {
                MessageBox.Show("Not authorized to access " + dirName);
                return;
            }
            catch (FileNotFoundException)
            {
                MessageBox.Show("No such directory: " + dirName);
                return;
            }
 
        // Init ListView and folder collection
            folderCol = new System.Collections.Specialized.StringCollection();
            CreateHeadersAndFillListView();
            PaintListView(dirName);
            folderCol.Add(dirName);
            //PaintListView(@"c:\c# testing");
            //folderCol.Add(@"c:\c# testing");
            //PaintListView(@"\\crprdnsrc03\logs$\sd4\regional");
            //folderCol.Add(@"\\crprdnsrc03\logs$\sd4\regional");
        }
 
         private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
        
        private void CreateHeadersAndFillListView()
        {
            ColumnHeader colHead;
 
            colHead = new ColumnHeader();
            colHead.Width = 500;
            colHead.Text = "Filename";
            this.lvwFilesAndFolders.GridLines = true;
            this.lvwFilesAndFolders.Columns.Add(colHead);
 
            colHead = new ColumnHeader();
            colHead.Width = 100;
            colHead.Text = "Size";
            this.lvwFilesAndFolders.GridLines = true;
            this.lvwFilesAndFolders.Columns.Add(colHead);
 
            colHead = new ColumnHeader();
            colHead.Width = 200;
            colHead.Text = "Last Accessed";
            this.lvwFilesAndFolders.GridLines = true;
            this.lvwFilesAndFolders.Columns.Add(colHead);
        }
 
        private void PaintListView(string root)
        {
            try
            {
                ListViewItem lvi;
                ListViewItem.ListViewSubItem lvsi;
 
                this.labelDisplayLogInfo.Text = root;
                DirectoryInfo dir = new DirectoryInfo(root);
 
                this.lvwFilesAndFolders.Items.Clear();
 
                DirectoryInfo[] dirs = dir.GetDirectories();
                FileInfo[] files = dir.GetFiles();
 
                this.lvwFilesAndFolders.BeginUpdate();
 
                foreach (System.IO.FileInfo fi in files)
                {
                    lvi = new ListViewItem();
                    lvi.Text = fi.Name;
                    //lvi.ImageIndex = 0;
                    lvi.Tag = fi.FullName;
 
                    lvsi = new ListViewItem.ListViewSubItem();
                    lvsi.Text = formatsizekb(fi.Length);
                    lvi.SubItems.Add(lvsi);
 
                    lvsi = new ListViewItem.ListViewSubItem();
                    lvsi.Text = fi.LastAccessTime.ToString();
                    lvi.SubItems.Add(lvsi);
 
                    this.lvwFilesAndFolders.Items.Add(lvi);
 
                    //Lets count the number of files
                    int file_count = 1;
                    foreach(FileInfo file in files)
                    {
                        this.labelFileCountDisplay.Text = Convert.ToString(file_count++);
                    }                                  
                }
 
                this.lvwFilesAndFolders.EndUpdate();
            }
            catch (System.Exception err)
            {
                MessageBox.Show("Error: " + err.Message);
            }
 
            this.lvwFilesAndFolders.View = View.Details;
        }
    
            private void lvwFilesAndFolders_ItemActive(object sender, System.EventArgs e)
        {
            ListView lvw = (ListView)sender;
            string filename = lvw.SelectedItems[0].Tag.ToString();
            Console.WriteLine(filename);
        }
 
        private void buttonExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
 
        //Formats File size
        private string formatsizekb(long lsize)
        {
            const int iKB = 1024;
            const long lMB = 1048576;
 
            if (lsize < iKB)
                return string.Format("{0:#,#} bytes", lsize);
            else if (lsize >= iKB && lsize < lMB) ;
                return string.Format("{0:#,#} KB", lsize / 1024);
        }
    }
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
 
 
        }
 
        private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
 
        }
 
        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
 
        }
                
    }
}

Open in new window

wally_davisAsked:
Who is Participating?
 
Tony McCreathConnect With a Mentor Technical SEO ConsultantCommented:
Worker threads are not allowed to directly alter Controls in Forms. You should use InvokeRequired and Invoke to get round this. Here's an example of the pattern normally used.
		protected void CallableFromWorker_Event(object sender, EventArgs e)
		{
			if (this.InvokeRequired)
			{
				this.Invoke(new EventHandler(this.CallableFromWorker_Event), new object[] {sender, e});
			}
			else
			{
				// can do GUI stuff safely here
			}
		}

Open in new window

0
 
malibuboatsCommented:
Remove the } on line 158.
0
 
wally_davisAuthor Commented:
why would I do that? That's the ending brace for private void bw_DoWork(object sender, DoWorkEventArgs e)
{
}
This is the routine I want to wrap around all the other routines (that would be called subroutines, that is, if it can be done) in order to perform the thread work on all the routines within it. I'm trying to figure out how I can do this or do I have to re-write my code to do it another way?
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
wally_davisAuthor Commented:
Additional information: I get a squggly line right after the line private void bw_DoWork(object sender, DoWorkEventArgs e)
{ <-- Squiggly appears here on line 58
/Code between Line 58 and Line 158 where the ending brace is for the DoWork routine.
The I get squigglys underneath the word "void" on Lines 165 and 170. (I've currently removed the Lines
159 through 163 so that the DoWork routine is not in my code twice).
0
 
malibuboatsCommented:
Just for my clearification when the bw_DoWork method is fired you want it to also fire off the other methods you have listed between line 58 and 158?
0
 
wally_davisAuthor Commented:
Correct
0
 
malibuboatsConnect With a Mentor Commented:
If that is the case you could just call those methods from the bw_DoWork method.  This will fire each of those methods when the bw_DoWork is called.
0
 
wally_davisAuthor Commented:
sorry, I know the syntax for calling a subroutine in VB.Net (i.e. Call MySub() ), and I can't find anything on how to call a subroutine in C#. Could you show me the syntax please?
0
 
malibuboatsCommented:
It looks like those methods are already being fired when the button click event is fired.  Lines 48 - 50.  The only thing that is not doing is closing the form, whic you can add at the end of the buton click event handler.
0
 
wally_davisAuthor Commented:
right, so I can move these methods outside of the Click event and then call them. What is the syntax for calling other statements?
0
 
wally_davisAuthor Commented:
There appears to be more challenges to the backgroundworker then first expected. I have controls that are loaded during some of these method routines and I'm getting an error "Error: Cross-thread operation not valid: Control 'lvwFilesAndFolders' access from a thread other than the thread it was created on".

This happens when the "private void PaintListView(string root)" method is called from the BackgroundWorker.DoWork Event,  and it has references to the ListView Control named "lvwFilesAndFolders".
How in the world do I get around this Cross-thread operation?
0
 
wally_davisAuthor Commented:
Tiggerito,
This was the final solution but you helped me tremendously so I'll aware you 300 points.
Malibuboats provided me with part of the other solution to actually use a Call within the DoWork Event handler. Thank you both.
0
 
wally_davisAuthor Commented:
Final solution ended up looking like this.
protected void bgw_DoWork(object sender, DoWorkEventArgs e)
        {            
            {
                this.Invoke(new MethodInvoker(delegate()
                {
                    progressBar1.PerformStep();

                    /* Lets call the other statements from here
                    to Perform Safe threading execution */
                    string dirName = textBoxSearchPath.Text;
                    folderCol = new System.Collections.Specialized.StringCollection();
                    PaintListView(dirName);
                    folderCol.Add(dirName);
                }));                                
            }                        
        }
0
All Courses

From novice to tech pro — start learning today.