WPF应用程序未释放内存或内存泄漏

时间:2018-01-19 11:28:01

标签: c# mysql wpf memory memory-leaks

我开发了一家餐馆的应用程序。这是一个销售管理系统。问题是,它在订单完成后没有释放内存。

销售页面设计位于tabcontrol下。在第一个标签中提交销售订单,在提交订单后,它会打开另一个付款标签。之后是打印收据。

通过提交许多订单,它将增加内存和更多更多。使用它两到三个小时后,由于内存使用量的增加,请自动关闭应用程序。

我使用MySql作为数据库。

完成销售订单,存储销售详细信息和使用下面的给定代码将付款详细信息导入数据库:

    /// //// Add sales item  ////////////Store into sales_item table //////////         
    public bool sales_item(string salesdate)
    {
        DataTable dt = new DataTable();
        dt = ((DataView)dgrvSalesItemList.ItemsSource).ToTable();
        int rows = dgrvSalesItemList.Items.Count;
        for (int i = 0; i < rows; i++)
        {
            //string SalesDate = dtSalesDate.Text;
            string trno = txtInvoice.Text;
            string itemid = dt.Rows[i].ItemArray[4].ToString();  //dgrvSalesItemList.Rows[i].Cells[4].Value.ToString();
            string itNam = dt.Rows[i][0].ToString(); // dt.Rows[i].Cells[0].Value.ToString();
            double qty = Convert.ToDouble(dt.Rows[i][2].ToString());
            double Rprice = Convert.ToDouble(dt.Rows[i][1].ToString());
            double total = Convert.ToDouble(dt.Rows[i][3].ToString());
            double dis = Convert.ToDouble(dt.Rows[i][7].ToString()); //discount rate
            double taxapply = Convert.ToDouble(dt.Rows[i][8].ToString());
            int kitchendisplay = Convert.ToInt32(dt.Rows[i][9].ToString());
            string notes = dt.Rows[i].ItemArray[10].ToString();


            // =================================Start=====  Profit calculation =============== Start ========= 
            // Discount_amount = (Retail_price * discount) / 100                    -- 49 * 3 / 100 = 1.47
            // Retail_priceAfterDiscount = Retail_price - Discount_amount           -- 49 - 1.47 = 47.53
            // Profit = (Retail_priceAfterDiscount * QTY )   - (cost_price * qty);  ---( 47.53 * 1 ) - ( 45 * 1) = 2.53

            string sqlprofit = "Select cost_price , discount  from  purchase  where product_id  = '" + itemid + "'";
            DataAccess.ExecuteSQL(sqlprofit);
            DataTable dt1 = DataAccess.GetDataTable(sqlprofit);

            double cost_price = Convert.ToDouble(dt1.Rows[0].ItemArray[0].ToString());
            double discount = Convert.ToDouble(dt1.Rows[0].ItemArray[1].ToString());

            double Discount_amount = (Rprice * discount) / 100.00;
            double Retail_priceAfterDiscount = Rprice - Discount_amount;
            double Profit = Math.Round((Retail_priceAfterDiscount - cost_price), 2); // old calculation (Retail_priceAfterDiscount * qty) - (cost_price * qty);
            // =================================Start=====  Profit calculation =============== Start =========  

            string ordertime = DateTime.Now.ToString("HH:mm");

            string sql1 = " insert into sales_item (sales_id,itemName,Qty,RetailsPrice,Total, profit,sales_time, itemcode , discount, taxapply, note, status, ordertime) " +
                          " values ('" + trno + "', '" + itNam + "', '" + qty + "', '" + Rprice + "', '" + total + "', '" + Profit + "', " +
                          " '" + salesdate + "', '" + itemid + "', '" + dis + "', '" + taxapply + "', '" + notes + "', '" + kitchendisplay + "', '" + ordertime + "')";
            DataAccess.ExecuteSQL(sql1);

            //update quantity Decrease from Stock Qty |  purchase Table
            if (txtInvoice.Text == "")
            {
                MessageBox.Show("please check sales no ");
            }
            else
            {

                string itemids = dt.Rows[i][4].ToString();
                double qtyupdate = Convert.ToDouble(dt.Rows[i][2].ToString());

                // Update Quantity
                string sqlupdateQty = "select product_quantity  from purchase where product_id = '" + itemids + "'";
                DataAccess.ExecuteSQL(sqlupdateQty);
                DataTable dtUqty = DataAccess.GetDataTable(sqlupdateQty);
                double product_quantity = Convert.ToDouble(dtUqty.Rows[0].ItemArray[0].ToString()) - qtyupdate;

                string sql = " update purchase set " +
                                " product_quantity = '" + product_quantity + "' " +
                                " where product_id = '" + itemids + "' ";
                DataAccess.ExecuteSQL(sql);
            }

        }
        return true;

    }

    /// //// Payment items Add  ///////////Store into Sales_payment table //////// 
    public void payment_item(string payamount, string changeamount, string dueamount, string salestype, string salesdate, string custid, string Comment)
    {
        string trno = txtInvoice.Text;
        //string payamount = lblTotalPayable.Text;
       // string changeamount = txtChangeAmount.Text;
      //  string due = txtDueAmount.Text;
        string vat = lblTotalVAT.Text;
        string DiscountTotal = lbloveralldiscount.Text; //lblTotalDisCount.Text;
       // string Comment = txtCustName.Text + " " + txtcomment.Text;
        string overalldisRate = txtDiscountRate.Text;
        string vatRate = txtVATRate.Text;
        string ordertime = DateTime.Now.ToString("HH:mm");
        string tableno = lblTableNo.Text;
        string tokenno = txttokenno.Text;

        string sql = "select MAX(sales_id) + 1 as sales_id from sales_payment";
        DataTable dtsales_id = DataAccess.GetDataTable(sql);

        double sales_id = Convert.ToDouble(dtsales_id.Rows[0].ItemArray[0].ToString());

        //MessageBox.Show("Sales Id = " + sales_id);

        string sql1 = " insert into sales_payment (sales_id, payment_type, payment_amount, change_amount, due_amount, dis, vat, " +
                        " sales_time, c_id, emp_id, comment, TrxType, Shopid , ovdisrate , vaterate, ordertime , tableno, tokenno ) " +
                        "  values ('" + sales_id + "','" + salestype + "', '" + payamount + "', '" + changeamount + "', " +
                        " '" + dueamount + "', '" + DiscountTotal + "', '" + vat + "', '" + salesdate + "', '" + custid + "', " +
                        " '" +  UserInfo.UserName + "','" + Comment + "','POS', '"+ UserInfo.Shopid +"', '" + overalldisRate + "' , '" + vatRate + "', " +
                        " '" + ordertime + "', '" + tableno + "', '" + tokenno + "' )";
        DataAccess.ExecuteSQL(sql1);
    }

    /// //// Token no Add  ///////////Store into tbl_tokenno table //////// 
    public void tokennoInsert()
    {
        string trno = txtInvoice.Text;
        string payamount = lblTotalPayable.Text;
        string tokenno = txttokenno.Text;

        string sqltkn = " insert into tbl_tokenno (sales_id, tokenno, sales_date) " +
                        "  values ('" + txtInvoice.Text + "','" + tokenno + "',   '" + dtSalesDate.Text + "' )";
        DataAccess.ExecuteSQL(sqltkn);
    }

使用下面给出的代码打印收据:

    //Sale and print
    private void btnCompleteSalesAndPrint_Click(object sender, RoutedEventArgs e)
    {
        if (txtPaidAmount.Text == "00" || txtPaidAmount.Text == "0" || txtPaidAmount.Text == string.Empty)
        {
            //  MessageBox.Show("Please insert paid amount", "Yes or No", MessageBoxButton.OK, MessageBoxImage.Warning);
            growlNotifications.AddNotification(new Notification { Title = "Alert Message", Message = "Please insert paid amount", ImageUrl = "pack://application:,,,/Notifications/Radiation_warning_symbol.png" });
            txtPaidAmount.Focus();
        } 
        else
        {
            try
            { 
                {
                    ////Save payment info into sales_payment table
                    payment_item(lblTotalPayable.Text, txtChangeAmount.Text, txtDueAmount.Text, CombPayby.Text, dtSalesDate.Text, lblCustID.Text, txtcomment.Text);

                    // save sales items one by one  
                    sales_item(dtSalesDate.Text);

                    //// TokennoInsert
                    tokennoInsert();

                    // Open Print Invoice
                    this.Visibility = Visibility.Hidden;
                    parameter.autoprint = "1";
                    Sales_Register.ReceiptPrint go = new Sales_Register.ReceiptPrint(txtInvoice.Text); 
                    {
                        string sqlinfo = "select sales_id,  sales_time, ordertime, tableno, tokenno  from sales_payment  where  sales_id = '" + txtInvoice.Text + "' ";
                        DataAccess.ExecuteSQL(sqlinfo);
                        DataTable dtinfo = DataAccess.GetDataTable(sqlinfo);

                        Grid Layout = new Grid();
                        Layout.FlowDirection = FlowDirection.LeftToRight;
                        Layout.Width = 280;
                        Layout.Height = 677;
                        Layout.VerticalAlignment = VerticalAlignment.Top;
                        RowDefinition ro1 = new RowDefinition();
                        RowDefinition ro2 = new RowDefinition();
                        ro1.Height = GridLength.Auto;

                        Layout.RowDefinitions.Add(ro1);
                        Layout.RowDefinitions.Add(ro2);
                        TextBlock ticketName = new TextBlock();
                        ticketName.Margin = new Thickness(0, 0, 0, 0);
                        ticketName.FontWeight = FontWeights.Bold;
                        ticketName.FontSize = 14;
                        ticketName.Text = "Ticket  : " + dtinfo.Rows[0].ItemArray[4].ToString();
                        ticketName.HorizontalAlignment = HorizontalAlignment.Center;
                        Grid.SetRow(ticketName, 0);
                        Layout.Children.Add(ticketName);

                        TextBlock Datetext = new TextBlock();
                        Datetext.Margin = new Thickness(20, 20, 0, 0); 
                        Datetext.Text = "Date : "+ dtinfo.Rows[0].ItemArray[1].ToString(); 
                        Grid.SetRow(Datetext, 0);

                        Layout.Children.Add(Datetext); 
                        TextBlock timelabel = new TextBlock();
                        timelabel.Margin = new Thickness(20, 40, 0, 0);  
                        timelabel.Text = "Time : " + dtinfo.Rows[0].ItemArray[2].ToString(); 
                        Grid.SetRow(timelabel, 0);

                        Layout.Children.Add(timelabel);

                        TextBlock tablenom = new TextBlock();
                        tablenom.Margin = new Thickness(20, 60, 0, 0); 
                        tablenom.FontSize = 14;
                        tablenom.Text = "Table : " + dtinfo.Rows[0].ItemArray[3].ToString(); 
                        Grid.SetRow(tablenom, 0);

                        Layout.Children.Add(tablenom);

                        TextBlock Invoiceno = new TextBlock();
                        Invoiceno.Margin = new Thickness(20, 80, 0, 0);
                        Invoiceno.FontSize = 14;
                        Invoiceno.Text = " Invoice no: " + dtinfo.Rows[0].ItemArray[0].ToString();
                        Grid.SetRow(Invoiceno, 0);

                        Layout.Children.Add(Invoiceno);

                        TextBlock dash = new TextBlock();
                        dash.Margin = new Thickness(0, 110, 0, 0);
                        dash.FontSize = 14;
                        dash.FontWeight = FontWeights.Bold;
                        dash.Text = " ----------------------------- ";
                        dash.HorizontalAlignment = HorizontalAlignment.Center;
                        Grid.SetRow(dash, 0);
                        Layout.Children.Add(dash);

                        System.Windows.Controls.PrintDialog Printdlg2 = new System.Windows.Controls.PrintDialog();

                        string sqlTikitem = "  select  CONCAT('- ', Qty, ' ', itemName) as 'Items'    from sales_item   where sales_id = '" + txtInvoice.Text + "' ";
                        DataAccess.ExecuteSQL(sqlTikitem);
                        DataTable dtTikitem = DataAccess.GetDataTable(sqlTikitem);

                        DataGrid dt11 = new DataGrid();
                        dt11.VerticalAlignment = VerticalAlignment.Top;
                        dt11.FontWeight = FontWeights.SemiBold;
                        dt11.Width = 230;
                        dt11.FontFamily = new FontFamily("Arial");
                        dt11.FontSize = 16;

                        dt11.CanUserSortColumns = false;
                        dt11.BorderThickness = new Thickness(0, 0, 0, 0);
                        dt11.CanUserAddRows = false;
                        dt11.GridLinesVisibility = DataGridGridLinesVisibility.None;
                        dt11.HeadersVisibility = DataGridHeadersVisibility.None;

                        dt11.ItemsSource = dtTikitem.DefaultView;
                        Grid.SetRow(dt11, 1);
                        Layout.Children.Add(dt11);
                        Size pageSize2 = new Size(Printdlg2.PrintableAreaWidth, Printdlg2.PrintableAreaHeight);
                        // Size pageSize = new Size(340, 194);
                        // sizing of the element.
                        Layout.Measure(pageSize2);
                        Layout.Arrange(new Rect(0, 0, pageSize2.Width, pageSize2.Height));
                        Printdlg2.MaxPage = 10;
                       Layout.UpdateLayout();
                        Printdlg2.PrintVisual(Layout, "Ticket_Print_" + DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss"));
                    }

                    System.Windows.Controls.PrintDialog Printdlg = new System.Windows.Controls.PrintDialog();                       
                    {
                        Size pageSize = new Size(Printdlg.PrintableAreaWidth, Printdlg.PrintableAreaHeight);
                        go.grdPrintPanel.Measure(pageSize);
                        go.grdPrintPanel.Arrange(new Rect(0, 0, pageSize.Width, pageSize.Height));
                        Printdlg.MaxPage = 10;
                        go.grdPrintPanel.UpdateLayout();
                        Printdlg.PrintVisual(go.grdPrintPanel, "C_Receipt_Print_" + DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss"));
                    }

                    tabPayment.Visibility = Visibility.Hidden;
                    t.Rows.Clear();
                    DiscountCalculation();
                    vatcal();
                    txtbarcodescan.Focus();

                    Sales_Register.SalesRegister goSalesPage = new Sales_Register.SalesRegister();
                    goSalesPage.Show();

                    growlNotifications.AddNotification(new Notification { Title = "Wow ", Message = "Transaction has been successfully done", ImageUrl = "pack://application:,,,/Notifications/notification-icon.png" });

                }

            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message);
            }

        }
    }

我已经使用ReSharper dotMemory测试了内存泄漏,但我无法理解它。

0 个答案:

没有答案