Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone !!

I have a problem using the backgroundworker thing. Simply put i try to show random images and a little clock telling since when the app i running. The problem start when I try to add some socket code to send a certain value to clients sockets.
It just takes too long and during that time, my UI freezes for approximatively one minute or so. I read and some people told me to try using a backgroundworker.
I don't get where I'm doing something bad but nothing really changed. My app still freezes and for the same amount of time. Here is my code. Is anyone seeing the problem ? What and here am I doing wrong ? Thanks a lot !!

What I have tried:

C#
using Npgsql;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ImageRandomizeforSenseIt
{
    public partial class ImageRandomize : Form
    {
        // How to deal with form moving without controlbox
        public const int WM_NCLBUTTONDOWN = 0xA1;
        public const int HT_CAPTION = 0x2;

        [System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
        [System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
        public static extern bool ReleaseCapture();
        // End How to deal with form moving without controlbox 
        
        // Declarations & Initialisations
        //string answer = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms", t.Hours, t.Minutes, t.Seconds, t.Milliseconds);
        public int duration = 0;

        public List List_Hours_To_Check = new List { };
        public int NextIndex = -1;
        public int affiche = 0;
        
        /*    debut zone socket     */
            TcpListener ServerSocket = new TcpListener(System.Net.IPAddress.Any, 8888) ;
            int requestCount = 0;
            TcpClient ClientSocket = default(TcpClient);
        /*    fin zone socket     */

        /**/
            BackgroundWorker bw = new BackgroundWorker();
        /**/

        public ImageRandomize()
        {
            InitializeComponent();
            this.BackColor = Color.FromArgb(57, 57, 60);

            var start = DateTime.Today;
            var nbparjour = (24 * 60) / ImageRandomizeforSenseIt.Properties.Settings.Default.DelaiChangementEnMn;
            var clockQuery = from offset in Enumerable.Range(0, nbparjour)
                             select start.AddMinutes(ImageRandomizeforSenseIt.Properties.Settings.Default.DelaiChangementEnMn * offset);
            foreach (var time in clockQuery)
                List_Hours_To_Check.Add(time.ToString("HH:mm"));

            LabelTotal.Text = "XX : XX";

            /**/
                //bw.DoWork += Bw_DoWork;
            // To report progress from the background worker we need to set this property
            bw.WorkerReportsProgress = false;
            // This event will be raised on the worker thread when the worker starts
            bw.DoWork += new DoWorkEventHandler(Bw_DoWork);
            /**/

            ServerSocket.Start();
        }

        //Do your Background-Work
        private void Bw_DoWork(object sender, DoWorkEventArgs e)
        {
            //string[] param = e.Argument as string[];
            string ee;
 
            //Process your long running  task
            try
            {
                if (ServerSocket.Pending() == true)
                {
                    ClientSocket = ServerSocket.AcceptTcpClient();
                    requestCount = requestCount + 1;

                    NetworkStream networkStream = ClientSocket.GetStream();

                    byte[] bytesFrom = new byte[(int)ClientSocket.ReceiveBufferSize];
                    networkStream.Read(bytesFrom, 0, (int)ClientSocket.ReceiveBufferSize);

                    string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                    dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));

                    string serverResponse = List_Hours_To_Check[NextIndex];
                    Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);

                    networkStream.Write(sendBytes, 0, sendBytes.Length);
                    networkStream.Flush();

                    ClientSocket.Close();
                }
            }
            catch (InvalidOperationException ex)
            {
                ee = ex.Message; 
                //MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (SocketException ex)
            {
                ee = ex.Message;
            }
            catch (Exception ex)
            {
                ee = ex.Message;
            }

            //e.Result = null; //Set your Result of the long running task
        }

        private void Send_Something_Complete()
        {
            try
            {
                if (ServerSocket.Pending() == true)
                {
                    ClientSocket = ServerSocket.AcceptTcpClient();
                    requestCount = requestCount + 1;

                    NetworkStream networkStream = ClientSocket.GetStream();

                    byte[] bytesFrom = new byte[(int)ClientSocket.ReceiveBufferSize];
                    networkStream.Read(bytesFrom, 0, (int)ClientSocket.ReceiveBufferSize);

                    string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                    dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));

                    string serverResponse = List_Hours_To_Check[NextIndex];
                    Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);

                    networkStream.Write(sendBytes, 0, sendBytes.Length);
                    networkStream.Flush();

                    ClientSocket.Close();
                }
            }
            catch (InvalidOperationException ex)
            {
                //MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (SocketException ex)
            {
                //MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        private void Timer_Duration_Tick(object sender, EventArgs e)
        {            
            duration = duration + Timer_Duration.Interval;
            //TimeSpan t = TimeSpan.FromMilliseconds(duration);
            //LabelDuration.Text = string.Format("{0:D2} : {1:D2} : {2:D2}",t.Hours, t.Minutes, t.Seconds);

            TimeSpan t = TimeSpan.FromMilliseconds(duration);
            LabelDuration.Text = string.Format("{0:D2} : {1:D2} : {2:D2}",
                                                    t.Hours,
                                                    t.Minutes,
                                                    t.Seconds);

            var TM = DateTime.Now.ToString("HH:mm");

            if ((((List_Hours_To_Check.FindIndex(x => x == TM) != -1))
                || ((List_Hours_To_Check.FindIndex(x => x == TM) == -1) && (picToZoom.Image == null)))
                && (affiche == 0))
            {
                NextIndex = List_Hours_To_Check.FindIndex(x => x == TM) + 1;
                affiche = 1;
                Module.Current_Image_To_Be_Annotated_Path = Module.Get_Random_Image_To_Be_Annotated_Path();
                Module.Auto_Size_Image(Image.FromFile(Module.Current_Image_To_Be_Annotated_Path), picToZoom, PictureBoxSizeMode.Zoom);
                //SaveImage();
            }
            else if ((List_Hours_To_Check.FindIndex(x => x == TM) == -1) && (picToZoom.Image != null))
            {
                Boolean NextFound = false;
                affiche = 0;
                while (NextFound == false)
                {
                    var TN = DateTime.Now.AddMinutes(1).ToString("HH:mm");

                    if (List_Hours_To_Check.FindIndex(x => x == TN) != -1)
                    {
                        NextFound = true;
                        NextIndex = List_Hours_To_Check.FindIndex(x => x == TN);
                    }
                    else
                    {
                        NextFound = false;
                    }
                }
            }

            LabelTotal.Text = List_Hours_To_Check[NextIndex];
            
            //Send_Something_Complete(); 
        }

        private void SaveImage()
        {
            // Save the selected image
            string Query_S = String.Empty;
            List listevaleurs = new List { };

            Query_S =
            "INSERT INTO image_affichee (image_en_cours, heure_image_suivante) " +
                "values (@a, @b);";

            listevaleurs.Add(Module.Current_Image_To_Be_Annotated_Path);
            listevaleurs.Add(LabelTotal.Text);

            NpgsqlConnection Connection = Module.Connexion();
            NpgsqlTransaction Transaction;

            Connection.Open(); if (!(Connection.State == ConnectionState.Open)) { Connection.Open(); }

            Transaction = Connection.BeginTransaction();
            NpgsqlCommand MaCommande = new NpgsqlCommand(Query_S, Connection, Transaction);

            try
            {
                MaCommande.Parameters.Add("@a", listevaleurs[0]);
                MaCommande.Parameters.Add("@b", listevaleurs[1]);
                MaCommande.ExecuteNonQuery();

                Transaction.Commit();
            }
            catch (NpgsqlException ex)
            {
                MessageBox.Show(("Error " + (ex.ErrorSql + (" has occurred: " + ex.Message))), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Transaction.Rollback();
            }

            if ((Transaction == null)) { Connection.Close(); }
        }        
                
        private void ImageRandomize_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ReleaseCapture();
                SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
            }
        }
        
        private void ImageRandomize_Load(object sender, EventArgs e)
        {
            // Adding the events to Form
            this.MouseDown += ImageRandomize_MouseDown;

            Timer_Duration.Start();
        }
        
        private void ImageRandomize_DoubleClick(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized; 
        }

        private void ImageRandomize_FormClosing(object sender, FormClosingEventArgs e)
        {
            ServerSocket.Stop();
        }

        private void ImageRandomize_Shown(object sender, EventArgs e)
        {
            bw.RunWorkerAsync();
        }
        
    }
}
Posted
Updated 9-May-18 4:44am
v2

1 solution

Hi everyone !!

I've come t an answer. The first problem was in my code, not the backgroundworker.

this part especially was the guilty one.

C#
Boolean NextFound = false;
                affiche = 0;
                while (NextFound == false)
                {
                    var TN = DateTime.Now.AddMinutes(1).ToString("HH:mm");

                    if (List_Hours_To_Check.FindIndex(x => x == TN) != -1)
                    {
                        NextFound = true;
                        NextIndex = List_Hours_To_Check.FindIndex(x => x == TN);
                    }
                    else
                    {
                        NextFound = false;
                    }
                }


I fixed it and i use thread now. Everything is working smoothly. Thank you !!
 
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