即使在使用背景工作者时,如何将UI置于冻结状态? [英] How do I top the UI from freezing even when I'm using a backgroundworker ?
问题描述
大家好!
我在使用backgroundworker时遇到了问题。简单地说,我尝试显示随机图像和一个小时钟告诉自从我运行的应用程序。当我尝试添加一些套接字代码以向客户端套接字发送特定值时,问题就出现了。
它只需要太长时间,在此期间,我的用户界面冻结大约一分钟左右。我看了,有些人告诉我尝试使用背景工作者。
我没有得到我做错事但没有真正改变的地方。我的应用程序仍然冻结并持续相同的时间。这是我的代码。有人看到这个问题吗?什么,我在做错了什么?非常感谢!!
我的尝试:
< pre lang =c#> 使用 Npgsql;
使用系统;
使用 System.Collections.Generic;
使用 System.ComponentModel;
使用 System.Data;
使用 System.Drawing;
使用 System.Linq;
使用 System.Text;
使用 System.Net.Sockets;
使用 System.Threading;
使用 System.Threading.Tasks;
使用 System.Windows.Forms;
命名空间 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();
// 结束如何处理没有控制框的表单移动
// 声明&初始化
// 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 ;
/ * 首次亮相区域套接字* /
TcpListener ServerSocket = new TcpListener(System.Net.IPAddress.Any, 8888 );
int requestCount = 0 ;
TcpClient ClientSocket = 默认(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 = 来自 offset 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;
// 要报告后台工作人员的进度,我们需要设置此属性
bw.WorkerReportsProgress = false ;
// 当工人启动时,将在工作线程上引发此事件
bw.DoWork + = new DoWorkEventHandler(Bw_DoWork);
/ * * /
ServerSocket.Start();
}
// 做背景工作
private void Bw_DoWork( object sender ,DoWorkEventArgs e)
{
// string [] param = e.Argument as string [ ];
string ee;
// 处理长期运行的任务
尝试
{
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];
字节 [] 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 (例外情况)
{
ee = ex.Message;
}
// e.Result = null; //设置长时间运行任务的结果
}
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];
字节 [] 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。消息,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 ))
{
布尔 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()
{
// 保存所选图片
string Query_S = String .Empty;
列表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事务;
Connection.Open(); if (!(Connection.State == ConnectionState.Open)){Connection.Open(); }
Transaction = Connection.BeginTransaction();
NpgsqlCommand MaCommande = new NpgsqlCommand(Query_S,Connection,Transaction);
尝试
{
MaCommande.Parameters.Add( @ a,listevaleurs [ 0 ]);
MaCommande.Parameters.Add( @ b,listevaleurs [ 1 跨度>]);
MaCommande.ExecuteNonQuery();
Transaction.Commit();
}
catch (NpgsqlException ex)
{
MessageBox.Show(( 错误 +(ex.ErrorSql +( : + ex.Message))), 错误,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(句柄,WM_NCLBUTTONDOWN,HT_CAPTION, 0 );
}
}
私有 void ImageRandomize_Load( object sender,EventArgs e)
{
// 将事件添加到表单
此 .MouseDown + = ImageRandomize_MouseDown;
Timer_Duration.Start();
}
私有 void ImageRandomize_DoubleClick( object sender,EventArgs e)
{
this .WindowState = FormWindowState.Minimized;
}
private void ImageRandomize_FormClosing( object sender,FormClosingEventArgs e)
{
ServerSocket.Stop();
}
私有 void ImageRandomize_Shown( object sender,EventArgs e)
{
bw.RunWorkerAsync();
}
}
}
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 (例外情况)
{
ee = ex.Message;
}
// e.Result = null; //设置长时间运行任务的结果
}
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];
字节 [] 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。消息,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 ))
{
布尔 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()
{
// 保存所选图片
string Query_S = String .Empty;
列表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事务;
Connection.Open(); if (!(Connection.State == ConnectionState.Open)){Connection.Open(); }
Transaction = Connection.BeginTransaction();
NpgsqlCommand MaCommande = new NpgsqlCommand(Query_S,Connection,Transaction);
尝试
{
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();
}
}
}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.
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 !!
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
{
// 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();
}
}
}
")); 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(); } } }
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.
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 !!
这篇关于即使在使用背景工作者时,如何将UI置于冻结状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!