Переглянути джерело

1. 计算放在子线程,不阻塞UI;2. 添加计算进度显示

tangs 7 роки тому
батько
коміт
5c7261c679

BIN
.vs/frequency/v15/.suo


BIN
.vs/frequency/v15/sqlite3/storage.ide


+ 14 - 15
frequency/Form1.Designer.cs

@@ -35,7 +35,7 @@
             this.calculate = new System.Windows.Forms.Button();
             this.seeResult = new System.Windows.Forms.Button();
             this.status = new System.Windows.Forms.Label();
-            this.label1 = new System.Windows.Forms.Label();
+            this.progress = new System.Windows.Forms.Label();
             this.SuspendLayout();
             // 
             // originButton
@@ -106,23 +106,23 @@
             this.status.TabIndex = 7;
             this.status.Text = "状态:";
             // 
-            // label1
+            // progress
             // 
-            this.label1.AutoSize = true;
-            this.label1.Location = new System.Drawing.Point(97, 129);
-            this.label1.MinimumSize = new System.Drawing.Size(60, 0);
-            this.label1.Name = "label1";
-            this.label1.Size = new System.Drawing.Size(65, 12);
-            this.label1.TabIndex = 8;
-            this.label1.Text = "计算未开始";
-            this.label1.Click += new System.EventHandler(this.label1_Click);
+            this.progress.AutoSize = true;
+            this.progress.Location = new System.Drawing.Point(97, 129);
+            this.progress.MinimumSize = new System.Drawing.Size(60, 0);
+            this.progress.Name = "progress";
+            this.progress.Size = new System.Drawing.Size(65, 12);
+            this.progress.TabIndex = 8;
+            this.progress.Text = "计算未开始";
+            this.progress.Click += new System.EventHandler(this.label1_Click);
             // 
             // Form1
             // 
             this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
             this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
             this.ClientSize = new System.Drawing.Size(397, 233);
-            this.Controls.Add(this.label1);
+            this.Controls.Add(this.progress);
             this.Controls.Add(this.status);
             this.Controls.Add(this.seeResult);
             this.Controls.Add(this.calculate);
@@ -133,6 +133,7 @@
             this.Name = "Form1";
             this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
             this.Text = "关键字频率";
+            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
             this.Load += new System.EventHandler(this.Form1_Load);
             this.ResumeLayout(false);
             this.PerformLayout();
@@ -152,11 +153,9 @@
         private System.Windows.Forms.Button calculate; // 计算按钮
         private System.Windows.Forms.Button seeResult; // 查看结果按钮
         private System.Windows.Forms.Label status;
-        private System.Windows.Forms.Label label1;
+        private System.Windows.Forms.Label progress;
+        private string progressStatus;
         private string path;
-
-        private long currentIndex;
-        private long totalNum;
     }
 }
 

+ 123 - 36
frequency/Form1.cs

@@ -10,22 +10,48 @@ using System.Windows.Forms;
 using System.IO;
 using log = Log.Log;
 using Excel = Microsoft.Office.Interop.Excel;
+using System.Threading;
 
 namespace frequency
 {
     public partial class Form1 : Form
     {
+        public long currentIndex;
+        public long totalNum;
+        public Dictionary<string, int> finalResult;
+
         public Form1()
         {
+            // init logger
             log.Init("frequency.log");
+
+            // init params
             path = System.Environment.CurrentDirectory;
+
+            // init component
             InitializeComponent();
+
+            // init ShowProgress
+            Thread.Sleep(1000);
+            Thread thread = new Thread(this.ShowProgress);
+            thread.IsBackground = true;
+            thread.Start();
         }
 
         private string[] originTextsOrder;
         private string[] originTextsInverse;
         private string[] targetTexts;
 
+        // progress status
+        const string CAL_WAIT = "wait";
+        const string CAL_RUNNING = "running";
+        const string CAL_ERROR = "error";
+        const string CAL_SUCCESS = "success";
+        const string CAL_EXPORT = "exporting";
+
+        public delegate void ChangeProgressStatus();
+        public delegate void CallBackDelegate();
+
         private void SelectOriginButton(object sender, EventArgs e)
         {
             var fileDialog = new OpenFileDialog();
@@ -62,23 +88,19 @@ namespace frequency
 
         private void Calculate_Click(object sender, EventArgs e)
         {
-            this.label1.Text = "计算中...";
-            this.label1.Refresh();
+            if (null == this.originTextPath || null == this.targetTextPath || "" == this.originTextPath.Trim() || "" == this.targetTextPath.Trim())
+            {
+                MessageBox.Show("请先选择文件");
+                return;
+            }
+
+            //this.progress.Text = "计算中...";
+            //this.progress.Refresh();
+            this.progressStatus = CAL_RUNNING;
             this.calculate.Enabled = false;
 
             var code = this.Calculate();
-            if (code != 0)
-            {
-                this.label1.Text = "计算出错";
-                this.label1.Refresh();
-            }
-            else
-            {
-                this.label1.Text = "计算完成";
-                this.label1.Refresh();
-            }
             Application.DoEvents();
-            this.calculate.Enabled = true;
         }
 
         private int Calculate()
@@ -104,21 +126,40 @@ namespace frequency
             this.CleanTarget();
 
             // look up
-            var result = this.Lookup();
-            log.D("Calculate_Click look up success with length: {0}", result.Count);
+            Thread runLoopUp = new Thread(Lookup);
+            CallBackDelegate cbd = LoopUpCallBack;
+            runLoopUp.Start(cbd);
+
+            log.D("Calculate_Click look up success");
 
             // write data to file
-            this.label1.Text = "导出数据中...";
-            this.label1.Refresh();
+            //this.progress.Text = "导出数据中...";
+            //this.progress.Refresh();
+            //this.progressStatus = CAL_EXPORT;
 
-            var msg = this.Write2Xlsx(result);
+            //var msg = this.Write2Xlsx(result);
+            //if ("" != msg)
+            //{
+            //    log.E("Calculate_Click write data to xlsx error: {0}", msg);
+            //    return 1;
+            //}
+            log.D("Calculate_Click write data to xlsx success");
+            return 0;
+        }
+
+        private void LoopUpCallBack()
+        {
+            progressStatus = CAL_EXPORT;
+            var msg = this.Write2Xlsx(finalResult);
             if ("" != msg)
             {
+                progressStatus = CAL_ERROR;
+                calculate.Enabled = true;
                 log.E("Calculate_Click write data to xlsx error: {0}", msg);
-                return 1;
+                return ;
             }
-            log.D("Calculate_Click write data to xlsx success");
-            return 0;
+            progressStatus = CAL_SUCCESS;
+            log.D("Calculate_Click write data to xlsx success with length: {0}", finalResult.Count);
         }
 
         private void SeeResult_Click(object sender, EventArgs e)
@@ -318,10 +359,10 @@ namespace frequency
         }
 
 
-        private Dictionary<string, int> Lookup()
+        private void Lookup(object o)
         {
             this.currentIndex = 0;
-            this.totalNum = this.originTextsOrder.Length + this.originTextsInverse.Length;
+            this.totalNum = this.targetTexts.Length *  this.originTextsOrder.Length + this.originTextsInverse.Length * this.targetTexts.Length;
             Dictionary<string, int> result = new Dictionary<string, int>();
             for (int i = 0; i < this.originTextsOrder.Length; i++)
             {
@@ -362,17 +403,22 @@ namespace frequency
                     }
                 }
             }
-            return result;
+            finalResult = result;
+            log.D("Lookup calcate success with length: {0}", result.Count);
+
+            var cbd = o as CallBackDelegate;
+            cbd();
+            return ;
         }
 
         private bool judge(string origin, string target)
         {
-            var strs = origin.Split('-');
+            var strs = origin.Split(new char[] { '-' }, 2, StringSplitOptions.None);
             if (strs.Length < 2)
             {
                 return false;
             }
-            if ((strs[0] + "-" + strs[1] == target) || (strs[0] + "--" + strs[1] == target))
+            if (target.Contains(strs[0] + "-" + strs[1]) || target.Contains(strs[0] + "--" + strs[1]))
             {
                 return true;
             }
@@ -405,14 +451,6 @@ namespace frequency
                 index++;
             }
 
-            //sheet.Cells[1, 1] = "Name";
-            //sheet.Cells[1, 2] = "Sex";
-            //for (int i = 2; i < 5; i++)
-            //{
-            //    sheet.Cells[i, 1] = "Name" + i;
-            //    sheet.Cells[i, 2] = "Sex" + i;
-            //}
-
             try
             {
                 sheet.SaveAs(filename);
@@ -439,12 +477,61 @@ namespace frequency
 
         }
 
-        private void showProgress()
+        private void ShowProgress()
         {
+
+            log.D("ShowProgress start successful");
             while (true)
             {
-                this.label1.Text = this.label1.Text;
+                if (this.IsHandleCreated)
+                {
+                    Invoke(new ChangeProgressStatus(ChangeStatus));
+                }
+                //log.D("currentIndex: {0}, totalNum: {1}", currentIndex, totalNum);
+                Thread.Sleep(1000);
+            }
+            log.D("ShowProgress had finished");
+        }
+
+        private void ChangeStatus()
+        {
+            string status = "";
+            if (CAL_WAIT == progressStatus || "" == progressStatus)
+            {
+                status = "计算未开始";
+            }
+            if (CAL_RUNNING == progressStatus)
+            {
+                status = string.Format("计算中...  {0}/{1}", currentIndex, totalNum);
             }
+            if (CAL_ERROR == progressStatus)
+            {
+                status = "计算出错";
+            }
+            if (CAL_EXPORT == progressStatus)
+            {
+                status = "导出数据中...";
+            }
+            if (CAL_SUCCESS == progressStatus)
+            {
+                status = "计算完成";
+            }
+
+            log.D("ChangeStatus with status {0}", status);
+            this.progress.Text = status;
+            this.progress.Refresh();
+
+            if (progressStatus ==  CAL_ERROR || progressStatus == CAL_SUCCESS)
+            {
+                this.calculate.Enabled = true;
+                this.calculate.Refresh();
+            }
+            
+        }
+
+        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
+        {
+            System.Environment.Exit(0);
         }
     }
 }