Click here to Skip to main content
15,908,675 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi Friends,

Just edited the code and made it a small program, sharing the below:

Once run the code, both the background workers work properly but in log file , some logs are missing.


C#
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.Globalization;


namespace BGTESTING
{
    public partial class Form1 : Form
    {
        private BackgroundWorker myWorker1 = new BackgroundWorker();
        private BackgroundWorker myWorker2 = new BackgroundWorker();
        private delegate void UpdateStatusDelegate();
        private UpdateStatusDelegate updateStatusDelegate = null;
        public static string mystatus;
        static int serverStatus = 0;
        public static string AppLogFile = "SG_LeadServer";
        public static string logPath = Directory.GetCurrentDirectory() + "\\LOGS\\" + DateTime.Now.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture).Replace("/", "");
        string strappPath = Directory.GetCurrentDirectory();
        public Form1()
        {
            InitializeComponent();
            myWorker1.DoWork += new DoWorkEventHandler(myWorker1_DoWork);
            myWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(myWorker1_RunWorkerCompleted);
            myWorker1.ProgressChanged += new ProgressChangedEventHandler(myWorker1_ProgressChanged);
            myWorker1.WorkerReportsProgress = true;
            myWorker1.WorkerSupportsCancellation = true;

            myWorker2.DoWork += new DoWorkEventHandler(myWorker2_DoWork);
            myWorker2.RunWorkerCompleted += new RunWorkerCompletedEventHandler(myWorker2_RunWorkerCompleted);
            myWorker2.ProgressChanged += new ProgressChangedEventHandler(myWorker2_ProgressChanged);
            myWorker2.WorkerReportsProgress = true;
            myWorker2.WorkerSupportsCancellation = true;
        }
        protected void myWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker sendingWorker = (BackgroundWorker)sender;
            object[] arrObjects = (object[])e.Argument;
            int maxValue = (int)arrObjects[0];
            for (int i = 1; i <= 20000000; i++)
            {
                if (!sendingWorker.CancellationPending)
                {
                    myWriteBC1(i);
                }
                else
                {
                    e.Cancel = true;
                    this.Invoke(this.updateStatusDelegate);
                    break;
                }
                //i = 1;
            }
        }
        protected void myWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (!e.Cancelled && e.Error == null)//Check if the worker has been cancelled or if an error occured
            {
                string result = (string)e.Result;//Get the result from the background thread
                mystatus = result;
                this.Invoke(this.updateStatusDelegate);
            }
            else if (e.Cancelled)
            {
                mystatus = "User Cancelled IN WORKER 1";
            }
            else
            {
                mystatus = "An error has occured";
                this.Invoke(this.updateStatusDelegate);
            }
            Startbutton.Enabled = true;//Reneable the start button
        }
        protected void myWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            mystatus = "go in Process changes loop....pradip..please look into this";
        }

        protected void myWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker sendingWorker = (BackgroundWorker)sender;
            object[] arrObjects = (object[])e.Argument;
            int maxValue = (int)arrObjects[0];
            for (int i = 3000000; i <= 20000000; i++)
            {
                if (!sendingWorker.CancellationPending)
                {
                    myWriteBC2(i);
                }
                else
                {
                    e.Cancel = true;
                    this.Invoke(this.updateStatusDelegate);
                    break;
                }
            }
        }
        protected void myWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (!e.Cancelled && e.Error == null)
            {
                string result = (string)e.Result;
                mystatus = result;
                this.Invoke(this.updateStatusDelegate);
            }
            else if (e.Cancelled)
            {
                mystatus = "User Cancelled IN WORKER 2";
            }
            else
            {
                mystatus = "An error has occured";
                this.Invoke(this.updateStatusDelegate);
            }
            Startbutton.Enabled = true;
        }
        protected void myWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            mystatus = "go in Process changes loop....pradip..please look into this";
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.updateStatusDelegate = new UpdateStatusDelegate(this.UpdateStatus);
            if (serverStatus == 0)
            {
                ServerStatustextBox.Text = "Stopped";
                Startbutton.Text = "Start";
            }
            else
            {
                Startbutton.Text = "Stop";
                ServerStatustextBox.Text = "Running";
            }
            mystatus = "Current Status: " + ServerStatustextBox.Text+" this is on form Load";

            this.Invoke(this.updateStatusDelegate);
        }

        private void Startbutton_Click(object sender, EventArgs e)
        {
            if (serverStatus == 0)
            {
                AppLogFile = "SG_LeadServer";
                serverStatus = 1;
                Startbutton.Text = "Stop";
                ServerStatustextBox.Text = "Running";
                if (!myWorker1.IsBusy)
                {
                    Int32 i = 1;
                    int numericValue = i;
                    object[] arrObjects = new object[] { numericValue };
                    myWorker1.RunWorkerAsync(arrObjects);
                }
                if (!myWorker2.IsBusy)
                {
                    Int32 i = 1;
                    int numericValue = i;
                    object[] arrObjects = new object[] { numericValue };
                    myWorker2.RunWorkerAsync(arrObjects);
                }
            }
            else if (serverStatus == 1)
            {
                    serverStatus = 0;
                    Startbutton.Text = "Start";
                    ServerStatustextBox.Text = "Stopped";
                    AppLogFile = "SG_LeadServer";
                    myWorker1.CancelAsync();
                    myWorker2.CancelAsync();
                    mystatus = "Stop Action Received for servID 8aa " + DateTime.Now.ToString();
            }
            mystatus = "Current Status: " + ServerStatustextBox.Text;
            this.Invoke(this.updateStatusDelegate);
        }
        public void UpdateStatus()
        {
            if (listBox1.Items.Count > 500) listBox1.Items.Clear();
            if (mystatus != "")
            {
                this.listBox1.Items.Insert(0, DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss") + " ==> " + mystatus);
                writeLogFile(logPath, AppLogFile, mystatus);
            }
            mystatus = "";
        }
        public void writeLogFile(string strLogPath, String strFileName, string strLogtxt)
        {
            if (!Directory.Exists(strLogPath))
            {
                Directory.CreateDirectory(strLogPath);
            }
            string strfullPath = strLogPath + "\\" + strFileName + ".txt";
            StreamWriter log;
            if (!File.Exists(strfullPath))
            {
                log = new StreamWriter(strfullPath);
            }
            else
            {
                log = File.AppendText(strfullPath);
            }
            log.WriteLine(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss") + " ==> " + strLogtxt);
            log.Close();
        }
        void myWriteBC1(int k)
        {
            AppLogFile = "LOG_BC1";
            mystatus = "This is in BC1_DoWork    " + k.ToString();
            this.Invoke(this.updateStatusDelegate);
            System.Threading.Thread.Sleep(500);
        }
        void myWriteBC2(int k)
        {
            AppLogFile = "LOG_BC2";
            mystatus = "This is in BC2_DoWork    " + k.ToString();
            this.Invoke(this.updateStatusDelegate);
            System.Threading.Thread.Sleep(500);
        }
       
    }
}


What I have tried:

I need to generate the log file backgroundworker wise and it should not mismatch.
Posted
Updated 5-Apr-16 23:43pm
v4
Comments
pradipkilledar 28-Mar-16 4:26am    
below are the steps: I did:
Just I need one more help:
below are the steps which I did:
1)created 5 backgroundworkers and it runs parallely.
2)crated one function to write the logs
3)created one public string veriable as "myLogText".
4)called the write log function in each background worker to write the logs
5)passing myLogText string in write log function
6)once run the program, app creates the log files backgroundworkerwise and write the logs but I realised that texts are mismatching..that means one log file created by backgroundworker1 but in text file text content are there from other background worksers also

please help me ...
Philippe Mori 30-Mar-16 23:26pm    
Well, you have to decide how your program should behave and then write code such that it works as expected.

If at this point, you don't know how to write working multithreaded program, better to use a single background worker and have code that work as expected...
OriginalGriff 28-Mar-16 4:34am    
Without seeing the relevant log code, there isn't really anything we can do.
Edit your question and show the relevant code fragments.

Use the "Improve question" widget to edit your question and provide better information.
RickZeeland 28-Mar-16 6:26am    
Take a look at ReaderWriterLockSlim, https://msdn.microsoft.com/nl-nl/library/system.threading.readerwriterlockslim(v=vs.110).aspx
Philippe Mori 30-Mar-16 23:21pm    
In that case, a lock won't help much as there is only one UI thread anyway...

That code does not make much sense... and it is not maintainable.

Some comments on the code. Lot more issues can be found:

1)If you use background workers, you probably don't need explicit Invoke. Use ReportProgress instead.

2) If you have more than 5 rows in your data, some row might not be processed as you do nothing if all worker are busy.

3) In your workers, you set i to 1 in each iteration. This will create an "infinite" loop but in a very obscur way. If you want an infinite loop, then don't use variable i.

4) It does not make much sense to report on i (commented out code), if the value is always 2 except the first one.

5) Spelling error in recived.

6) Way too much duplicate code. Have you ever read on DRY?
Don't repeat yourself - Wikipedia, the free encyclopedia[^]
Don't Repeat Yourself - Programmer 97-things[^]
Dont Repeat Yourself[^]

7)Your functions are too complicate. You should read articles on SRP.
Single responsibility principle - Wikipedia, the free encyclopedia[^]
SOLID: Part 1 - The Single Responsibility Principle[^]
Single Responsibility Principle | Object Oriented Design[^]
SOLID Principles: Single Responsibility Principle -> What, Why and How.[^]

8) Avoid hard-coded constants in code. You have a bunch of them in your code:
500 (maximum number of items in list)
1 (some server status)
"SG_LeadServer" (hard-coded string)
At the very minimum, put constants at class level so you have single and easy to find place to find them and only one value to update if you change your mind.

9) Avoid useless comments like this one: //Issue a cancellation request to stop the background worker. Comment should not repeat the (obvious) code (except for teaching purpose in school book).

10) If you have 5 threads, then it does not make sense that all of them update the same status. You should probably display a cumulative status in your case.

11) Delay in background worker is often suspicious. Why would you want to slow down processing.

12) You should remove obsolete code or put it inside #if obsolete_code / #endif or at least add a comment about why the code was commented out. In a forum such unused code is not really helpful although it give us some hint about what you try but we still don't know why it was commented out.

13) I don't see the purpose of the lock (code that use it is commented out). As you are calling Invoke from the DoWork handler, you already know that a single thread will be executing that code at the same time (assuming no other thread directly call the code --- in which case, the code would fails anyway because of cross-thread calls to UI).

14) Even worst is the fact that the code is hard-code to work with 5 workers. If one want to try with more or less workers to see the effect on performance, it is hard to adapt the code.

15) You should avoid mixing non UI code and UI code in the same class. This is even more the case here where code for each worker is more or less a copy of the code of other workers. In such case, you should have at least 2 classes... Code in the UI should be minimalist. If you ever want to port code on other platform (iOS, ASP.NET, Android, UWP, WPF,...) you want to share as much as possible code.
 
Share this answer
 
Comments
Philippe Mori 30-Mar-16 23:33pm    
And by the way, in that case, it might be more appropriate to use something else than a background worker... C# has many options for parallels computing but I'm not an expert in that since in my case, often it is not obvious to run parts in parallel since my processing is mainly sequential. Thus I usually use a single background worker and report progress each time the progress increase by at least one percent.
pradipkilledar 1-Apr-16 4:02am    
Hi,

Really appreciate for your revert....thanks ,OK will cleaning the code and will get back to you soon
Use "lock" statement.
lock Statement (C# Reference)[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900