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:
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
{
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();
public int duration = 0;
public List List_Hours_To_Check = new List { };
public int NextIndex = -1;
public int affiche = 0;
TcpListener ServerSocket = new TcpListener(System.Net.IPAddress.Any, 8888) ;
int requestCount = 0;
TcpClient ClientSocket = default(TcpClient);
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.WorkerReportsProgress = false;
bw.DoWork += new DoWorkEventHandler(Bw_DoWork);
ServerSocket.Start();
}
private void Bw_DoWork(object sender, DoWorkEventArgs e)
{
string ee;
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;
}
catch (SocketException ex)
{
ee = ex.Message;
}
catch (Exception ex)
{
ee = ex.Message;
}
}
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)
{
}
catch (SocketException ex)
{
}
catch (Exception ex)
{
}
}
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);
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);
}
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];
}
private void SaveImage()
{
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)
{
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();
}
}
}