c# - 工作 1-2 小时后应用程序开始冻结且无响应
问题描述
我使用 C# 和 SQL 服务器开发了一个 WinForm 应用程序,当我在我的计算机上测试它时,该应用程序运行完美,没有任何问题,它运行良好,我还改进了 Ram 使用率,最大 ram 使用量为 200 MB 我几乎检查了所有内容,但是在客户端 POS 机器上,应用程序在高峰时间工作 1-2 小时后开始冻结并且没有响应我的 clint 有 POSBANK 机器 4G 内存,我正在使用本地网络服务器和 SQL Server 2019 我不'不知道这是来自数据库连接还是计算机资源使用情况。
我对一些代码有顾虑,我使用 2flowLayoutPanel
个类别从数据库中获取所有类别并将其显示为按钮,flowLayoutPanel1
另一个获取所选类别下的所有材料并将它们显示在另一个flowLayoutPanel2
材料中门票是自定义usercontrol
的,包含一个 PictureBox 和 2 个标签(一个用于材料名称,另一个用于价格)。
这是我如何填写这些flowLayoutPanel
: 材料flowLayoutPanel
:
/// <summary>
/// GET MATERIAL SECTION START
/// </summary>
/// <param name="CategoryID"></param>
private void Show_Food_UC(int CategoryID, int page_number)
{
try
{
for (int i = flowLayoutPanel2.Controls.Count - 1; i >= 0; i--) { flowLayoutPanel2.Controls[i].Dispose(); GC.Collect(); }
using (SqlDataReader reader = DBConn.ExecuteReader("get_materials_uc", CommandType.StoredProcedure,
new SqlParameter[]
{
new SqlParameter("@page_num", page_number),
new SqlParameter("@page_rows", PAGESIZE),
new SqlParameter("@categid", CategoryID),
}
))
{
while (reader.Read())
{
Food_uc UC = new Food_uc
{
Material_barcode = reader["barcode"].ToString(),
Material_Price = Convert.ToDecimal(reader["sell_price"].ToString()),
Material_name = reader["name"].ToString()
};
if (reader["image"] != DBNull.Value)
{
byte[] image = (byte[])reader["image"];
image = Decompress(image);
using (var stream = new MemoryStream())
{
stream.Write(image, 0, image.Length);
var bitmap = new Bitmap(stream);
UC.Material_image = bitmap;
}
}
UC.MaterialImage.Click += UC_PictureBox1_Click;
UC.Material_name_txt.Click += UC_PictureBox1_Click;
//UC.MaterialImage.MouseDown += UC_PictureBox1_MouseDown;
//UC.Material_name_txt.MouseDown += UC_PictureBox1_MouseDown;
//UC.MaterialImage.MouseMove += UC_PictureBox1_MouseMove;
//UC.Material_name_txt.MouseMove += UC_PictureBox1_MouseMove;
flowLayoutPanel2.Controls.Add(UC);
//bitmap.Dispose();
}
}
ROWCOUNT = Convert.ToInt32(DBConn.ExecuteScaler("select count(categid) from materials where categid=@categid", CommandType.Text, new SqlParameter[] { new SqlParameter("@categid", CategoryID.ToString()) }));
MAXPAGE = (int)Math.Ceiling(Convert.ToDecimal(ROWCOUNT / PAGESIZE) - 1);
if (MAXPAGE < 0)
{
MAXPAGE = 0;
}
Barcode_txt.Select();
if (PAGE_number == MAXPAGE)
{
Next_but.Enabled = false;
}
else
{
Next_but.Enabled = true;
}
if (PAGE_number == 0)
{
Back_but.Enabled = false;
}
else
{
Back_but.Enabled = true;
}
}
catch (SqlException ex)
{
// Do some logging or something.
MessageBox.Show("There was an error accessing your data. DETAIL: " + ex.Message);
}
}
/// <summary>
/// decompress image
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static byte[] Decompress(byte[] data)
{
MemoryStream input = new MemoryStream(data);
MemoryStream output = new MemoryStream();
using (DeflateStream dstream = new DeflateStream(input, CompressionMode.Decompress))
{
dstream.CopyTo(output);
}
return output.ToArray();
}
这是材料用户控制代码:
public partial class Food_uc : UserControl
{
public Food_uc()
{
InitializeComponent();
Material_name_txt.Parent = MaterialImage;
Material_name_txt.Dock = DockStyle.Bottom;
Material_name_txt.BackColor = Color.FromArgb(80, 0,0,0);
Price_txt.Parent = MaterialImage;
Price_txt.BackColor = Color.FromArgb(200, 108, 99, 255);
}
public string Material_name { get; set; }
public decimal Material_Price { get; set; }
public Image Material_image { get; set; }
public string Material_barcode { get; set; }
private void Food_uc_Load(object sender, EventArgs e)
{
Price_txt.Text = Material_Price.ToString("C1");
Material_name_txt.Text = Material_name;
Material_name_txt.Tag = Material_barcode;
MaterialImage.Tag = Material_barcode;
if (Material_image != null)
{
MaterialImage.Image = Material_image;
//Material_image.Dispose();
}
}
private void Price_txt_TextChanged(object sender, EventArgs e)
{
Price_txt.Width = TextRenderer.MeasureText(Price_txt.Text, Price_txt.Font).Width;
}
private void Food_uc_ControlRemoved(object sender, ControlEventArgs e)
{
if (Material_image != null)
{
Material_image.Dispose();
}
}
}
这是类别flowLayoutPanel
:
/// <summary>
/// GET CATEGORIES SECTION START
/// </summary>
int cunt = 0;
private void Get_Categories()
{
try
{
for (int i = flowLayoutPanel1.Controls.Count - 1; i >= 0; i--) { flowLayoutPanel1.Controls[i].Dispose(); GC.Collect(); }
using (SqlDataReader reader = DBConn.ExecuteReader("search_categories", CommandType.StoredProcedure, new SqlParameter[] { new SqlParameter("@name", Categories_search_txt.Text.Trim()) }))
{
while (reader.Read())
{
cunt = +cunt;
Guna.UI2.WinForms.Guna2Button button = new Guna.UI2.WinForms.Guna2Button
{
Animated = false,
BorderRadius = 5,
FillColor = Color.FromArgb(108, 99, 255),
Font = new Font("Droid Arabic Kufi", 12F, FontStyle.Regular, GraphicsUnit.Point, 0),
ButtonMode = Guna.UI2.WinForms.Enums.ButtonMode.RadioButton
};
button.CheckedState.FillColor = Color.FromArgb(61, 54, 144);
button.Anchor = (AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Top);
button.Height = 50;
button.Width = 140;
button.Tag = reader["ID"];
button.Text = reader["name"].ToString();
button.Click += FLB_Click;
button.MouseDown += FLB_MouseDown;
button.MouseMove += FLB_MouseMove;
flowLayoutPanel1.Controls.Add(button);
}
}
}
catch (SqlException ex)
{
// Do some logging or something.
MessageBox.Show("There was an error accessing your data. DETAIL: " + ex.Message);
}
}
int DownAt;
bool Moved = false;
//private object mprcTabTip;
private void FLB_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
DownAt = e.Y;
}
private void FLB_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
int yy = Math.Abs(flowLayoutPanel1.AutoScrollPosition.Y);
yy += DownAt - e.Y;
if (yy > flowLayoutPanel1.AutoScrollPosition.Y + 1 | yy < flowLayoutPanel1.AutoScrollPosition.Y - 1)
Moved = true;
flowLayoutPanel1.AutoScrollPosition = new Point(0, yy);
}
}
private void FLB_Click(object sender, EventArgs e)
{
if (!Moved)
{
PAGE_number = 0;
CATEGORYID = (int)(sender as Guna.UI2.WinForms.Guna2Button).Tag;
Show_Food_UC(CATEGORYID, PAGE_number);
}
else
{
Moved = false;
}
}
这是我的 SQL 类助手:
class DBConn
{
static string ConnectionString;
private static void DBConnn()
{
if (Settings.Default.Trusted_Connection == false)
{
ConnectionString = string.Format("Server = {0}; Database={1}; User Id={2};Password={3};MultipleActiveResultSets=true", Settings.Default.server, Settings.Default.database, Settings.Default.user, Settings.Default.password);
}
else
{
ConnectionString = string.Format("Server = {0}; Database={1}; Trusted_Connection=True;MultipleActiveResultSets=true", Settings.Default.server, Settings.Default.database);
}
}
public static bool Check_Connection()
{
DBConnn();
using (SqlConnection connStr = new SqlConnection(ConnectionString))
{
try
{
connStr.Open();
return true;
}
catch (Exception)
{
return false;
}
}
}
public static DataTable ExecuteDataTable(string sql, CommandType cmdType, params SqlParameter[] parameters)
{
using (DataTable dt = new DataTable())
using (SqlConnection connStr = new SqlConnection(ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, connStr))
{
cmd.CommandType = cmdType;
cmd.Parameters.AddRange(parameters);
try
{
cmd.Connection.Open();
new SqlDataAdapter(cmd).Fill(dt);
}
catch (SqlException ex)
{
//log to a file or Throw a message ex.Message;
MessageBox.Show("Error: " + ex.Message);
}
return dt;
}
}
public static DataSet ExecuteDataSet(string sql, CommandType cmdType, params SqlParameter[] parameters)
{
using (DataSet ds = new DataSet())
using (SqlConnection connStr = new SqlConnection(ConnectionString))//ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, connStr))
{
cmd.CommandType = cmdType;
cmd.Parameters.AddRange(parameters);
try
{
cmd.Connection.Open();
new SqlDataAdapter(cmd).Fill(ds);
}
catch (SqlException ex)
{
//log to a file or Throw a message ex.Message;
MessageBox.Show("Error: " + ex.Message);
}
return ds;
}
}
public static DataSet ExecuteDataSet_Paging(string sql, int _Start, int _MaxObj, string Table, CommandType cmdType, params SqlParameter[] parameters)
{
using (DataSet ds = new DataSet())
using (SqlConnection connStr = new SqlConnection(ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, connStr))
{
cmd.CommandType = cmdType;
cmd.Parameters.AddRange(parameters);
//cmd.Parameters.Add(new SqlParameter("@RecordCount", SqlDbType.Int));
//cmd.Parameters["@RecordCount"].Direction = ParameterDirection.Output;
try
{
cmd.Connection.Open();
new SqlDataAdapter(cmd).Fill(ds, _Start, _MaxObj, Table);
//Int32 intRecCount = Convert.ToInt32(cmd.Parameters["@RecordCount"].Value);
//MessageBox.Show(intRecCount.ToString());
}
catch (SqlException ex)
{
//log to a file or Throw a message ex.Message;
MessageBox.Show("Error: " + ex.Message);
}
return ds;
}
}
public static void InsertUpdate_Data(string sql, CommandType cmdType, params SqlParameter[] parameters)
{
using (SqlConnection connStr = new SqlConnection(ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, connStr))
{
cmd.CommandType = cmdType;
cmd.Parameters.AddRange(parameters);
try
{
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
//log to a file or Throw a message ex.Message;
MessageBox.Show("Error: " + ex.Message);
}
}
}
public static string ExecuteScaler(string sql, CommandType cmdType, params SqlParameter[] parameters)
{
try
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.CommandType = cmdType;
cmd.Parameters.AddRange(parameters);
var result = Convert.ToString(cmd.ExecuteScalar());
return result;
}
}
}
catch (SqlException ex)
{
//log to a file or Throw a message ex.Message;
MessageBox.Show("Error: " + ex.Message);
throw;
}
}
public static int ExecuteScaler_ReturnValue(string sql, CommandType cmdType, params SqlParameter[] parameters)
{
try
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.CommandType = cmdType;
cmd.Parameters.AddRange(parameters);
var returnParameter = cmd.Parameters.Add("@inv_id", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
var result = returnParameter.Value;
return Convert.ToInt32(result);
}
}
}
catch (SqlException ex)
{
//log to a file or Throw a message ex.Message;
MessageBox.Show("Error: " + ex.Message);
throw;
}
}
public static bool Exists(string sql, CommandType cmdType, params SqlParameter[] parameters)
{
bool result = false;
using (SqlConnection connStr = new SqlConnection(ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, connStr))
{
cmd.CommandType = cmdType;
cmd.Parameters.AddRange(parameters);
try
{
cmd.Connection.Open();
cmd.ExecuteNonQuery();
result = Convert.ToBoolean(cmd.ExecuteScalar());
return result;
}
catch (SqlException ex)
{
//log to a file or Throw a message ex.Message;
MessageBox.Show("Error: " + ex.Message);
}
return result;
}
}
// Set the connection, command, and then execute the command with query and return the reader.
public static SqlDataReader ExecuteReader(String commandText, CommandType commandType, params SqlParameter[] parameters)
{
SqlConnection conn = new SqlConnection(ConnectionString);
using (SqlCommand cmd = new SqlCommand(commandText, conn))
{
cmd.CommandType = commandType;
cmd.Parameters.AddRange(parameters);
cmd.Connection.Open();
// When using CommandBehavior.CloseConnection, the connection will be closed when the
// IDataReader is closed.
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
}
public static void Delete(String commandText, CommandType commandType, params SqlParameter[] parameters)
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(commandText, conn))
{
cmd.CommandType = commandType;
cmd.Parameters.AddRange(parameters);
cmd.ExecuteReader();
}
}
}
}
解决方案
推荐阅读
- javascript - HTML+JS/jQuery:有没有办法将元素的值附加到表单操作字符串?
- python - 通过迭代嵌套字典中的第 n 级值来创建数据框
- apache-spark - 在 PySpark 上寻找更好的性能
- typescript - 带有 Typescript 的 React-Native 自定义文本组件:“将 React.ReactNode 类型转换为文本类型......”
- ibm-cloud - 为什么我在尝试创建存储时看到“经销商渠道 2c95500b-ea86-4b13-8bb5-b2f0c2fa8200 无效”错误
- graphql - Shopify GraphQL 以获取产品的交付率
- python - 切片 Django Queryset 字段值
- python - 如何在没有额外查询的情况下过滤反向相关字段?
- express - 上传到s3后如何返回文件位置
- qlikview - 使用服务器端扩展时,Qlik(查看或感知)过滤器在图表上显示数据(X 轴)