Как мне защитить пользовательский интерфейс от замораживания, даже если я использую backgroundworker ?
Всем привет !!
У меня есть проблема с использованием backgroundworker. Проще говоря, я пытаюсь показать случайные изображения и немного часов, говорящих с тех пор, как приложение я запустил. Проблема начинается, когда я пытаюсь добавить некоторый код сокета для отправки определенного значения в клиентские сокеты.
Это просто занимает слишком много времени, и в течение этого времени мой пользовательский интерфейс зависает примерно на одну минуту или около того. Я читал, и некоторые люди сказали мне попробовать использовать backgroundworker.
Я не понимаю, где я делаю что-то плохое, но на самом деле ничего не изменилось. Мое приложение все еще зависает и на то же время. Вот мой код. Кто - нибудь видит проблему ? Что и здесь я делаю не так ? Большое спасибо !!
Что я уже пробовал:
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(); } } }