首页 新闻 搜索 专区 学院

C#winform未响应问题,过段时间后恢复正常

0
悬赏园豆:10 [待解决问题]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Collections;
using System.Threading;
using System.Timers;
using System.Xml;
using System.Runtime.InteropServices;
using System.Data.SqlClient;
using System.Configuration;

namespace 串口通信
{
    public partial class Form1 : Form
    {
        public bool isFirstTimeToStart = true;
        private int timeStamp = 50;

        public Form1()
        {   
            InitializeComponent();   
        }
        /// <summary>
        /// 初始化串口属性
        /// </summary>
        /// 
        public void InitializeSerialPort()
        {
            if (isFirstTimeToStart == true)
            {
                port.DataBits = 8;
                port.PortName = ConfigurationManager.AppSettings["port"].ToString();    //设置串口为App.config配置
                port.BaudRate = 19200;
                port.DiscardNull = false;
                port.DtrEnable = false;
                port.Handshake = Handshake.None;
                port.Parity = Parity.None;
                port.ParityReplace = Convert.ToByte("63");
                port.RtsEnable = false;
                port.StopBits = StopBits.One;
                isFirstTimeToStart = false;

            }
        }

        //private void comboBox1_DropDown(object sender, EventArgs e)
        //{
        //    ///加载计算机上所有的COM串口
        //    comboBox1.Items.Clear();
        //    string[] ports = SerialPort.GetPortNames();
        //    foreach (string p in ports)
        //    {
        //        comboBox1.Items.Add(p);
        //    }
        //}

        ////打开串口
        //private void button1_Click(object sender, EventArgs e)
        //{
        //    InitializeSerialPort();
        //    port.Open();
        //    port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
        //}

        //执行串口方法
        void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            ArrayList array = new ArrayList();
            READAGAIN:
                while (port.BytesToRead > 0)
                {
                    array.Add((byte)port.ReadByte());
                }
                Thread.Sleep(timeStamp);
                if (port.BytesToRead > 0)
                {
                    goto READAGAIN;
                }
                InitializedListView2(array);
        }
        delegate void SetInfo(ArrayList infos);

        //lable显示状态
        public void InitializedListView2(ArrayList arrayList)
        {
            try
            {
                if (this.label2.InvokeRequired)
                {
                    SetInfo ss = new SetInfo(InitializedListView2);
                    this.Invoke(ss, new object[] { arrayList });
                }
                else
                {
                    byte[] data = new byte[arrayList.Count + 1];
                    string str = "";
                    for (int i = 0; i < arrayList.Count; i++)
                    {
                        data[i] = (byte)(arrayList[i]);
                        string aa = data[i].ToString("X");
                        str += (data[i].ToString("X").Length == 2 ? data[i].ToString("X") : "0" + data[i].ToString("X")) + " ";
                    }
                    if (str.Trim().Equals("00 1E 98"))

                    {
                        label2.Text = "离开红外感应!";
                    }
                    else if (str.Trim().Equals("00 1E 9E"))
                    {
                        label2.Text = "进入红外感应!";
                        //初始化方法名,并调用方法
                        Operater op = new Operater();
                        op.QueryStuNameById();
                    }
                    else
                    {
                        label2.Text = "";
                    }
                    //通过App.config调用程序休眠时间
                    int sleepTime = Convert.ToInt32(ConfigurationManager.AppSettings["sleepTime"]);
                    Thread.Sleep(sleepTime);
                    textBox1.Text += str + "\r\n";
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        //显示当前串口状态
        protected void DataReceived(string info)
        {
            switch (info)
            {
                case "00 1E 98":
                    label2.Text = "离开红外感应!";
                    break;
                case "00 1E 9E":
                    label2.Text = "进入红外感应!";
                    break;
                default:
                    label2.Text = "错误!";
                    break;
            }
        }

        //鼠标双击图标,弹出程序界面
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Show();
                this.WindowState = FormWindowState.Normal;
                this.Activate();
            }
        }
       
        //窗体加载事件
        private void Form1_Load(object sender, EventArgs e)
        {
            //加载窗体,打开串口
            InitializeSerialPort();
            port.Open();
            port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Visible = false;
            }
        }

        //private static void OnTimedEvent(object source, ElapsedEventArgs e)
        //{
        //    Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
        //}

        //鼠标双击图标,显示界面
        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            this.Visible = true;
            this.TopMost = true;
            this.WindowState = FormWindowState.Normal;
            this.Activate();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)  //关闭按钮事件
        {
            e.Cancel = true;
            this.Hide();
        }

        //最小化到托盘
        private void Form1_SizeChanged(object sender, EventArgs e)     //最小化事件按钮
        {
            this.Hide();
        }

        //托盘右键显示
        private void hideMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.Activate();
        }

        //托盘右键隐藏
        private void showMenuItem_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        //托盘右键退出
        private void exitMenuItem_Click_1(object sender, EventArgs e)
        {
            if (MessageBox.Show("你确定要退出终端服务程序吗?", "确认", MessageBoxButtons.OKCancel,
                MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
            {
                notifyIcon1.Visible = false;
                this.Close();
                this.Dispose();
                Application.Exit();
            }      
        }

        //存储过程方法
        public class Operater
        {
            private string ConStr = ConfigurationManager.AppSettings["Sqlconn"].ToString();     //设置Sql链接为App.config配置
            private SqlConnection sqlCon = null;
            private SqlCommand sqlComm = null;
            public void QueryStuNameById()
            {
                try
                {
                    using (sqlCon = new SqlConnection(ConStr))
                    {
                        sqlCon.Open();
                        sqlComm = new SqlCommand("usp_CallSceneStep", sqlCon);
                        //设置命令的类型为存储过程
                        sqlComm.CommandType = CommandType.StoredProcedure;
                        //设置参数
                        sqlComm.Parameters.Add("@SceneID", SqlDbType.Int);
                        //注意输出参数要设置大小,否则size默认为0,
                        sqlComm.Parameters.Add("@Step", SqlDbType.Int);
                        //为参数赋值
                        sqlComm.Parameters["@SceneID"].Value = ConfigurationManager.AppSettings["qjh"].ToString();
                        sqlComm.Parameters["@Step"].Value = "-1";
                        //执行
                        sqlComm.ExecuteNonQuery();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
    }   
}

程序倒是没有问题,就是执行的时候,红外探头感应到手势,会出现几秒钟的程序未响应问题,该如何优化?望各位大神帮忙解决下~谢谢
董毛毛的主页 董毛毛 | 初学一级 | 园豆:122
提问于:2013-12-18 11:01
< >
分享
所有回答(6)
0

把你的接收数据的代码放到 BackgroundWorker 中去执行。

Launcher | 园豆:45045 (高人七级) | 2013-12-18 11:16

这个可用

支持(0) 反对(0) 毋忆典藏 | 园豆:202 (菜鸟二级) | 2015-10-15 16:11
0

把执行串口方法用委托的方式去执行就不会出现这种情况了。

Jarrett.zhou | 园豆:69 (初学一级) | 2013-12-18 11:25
1

要么有阻塞的操作,要么有长时间的循环。

阻塞的操作有两个办法:1.异步。2.新开一线程。

长时间的循环也有两个办法:1.在循环中加入Application.Dovents()。2.新开一线程

空明流光 | 园豆:69 (初学一级) | 2013-12-18 11:36
0

UI线程做了一个很好时间的事情,所以你还是另外用一个线程完成吧

【秦时明月】 | 园豆:847 (小虾三级) | 2013-12-18 13:25
0

我一看这么长的代码,我就猜是毛毛,使用另一线程处理,要不要代码?

幕三少 | 园豆:1384 (小虾三级) | 2013-12-18 16:37

要代码~哈哈哈

支持(0) 反对(0) 董毛毛 | 园豆:122 (初学一级) | 2013-12-18 17:16
0

你那界面是假死。。由于占用了主线程。。导致假死。。所以你得用多线程。

Thread thread=new Thread(()=>{

 存储过程的方法

});

thread.Start();//启动线程

thread.IsBackground=true;//后台运行

在 水 一 方 | 园豆:1097 (小虾三级) | 2013-12-20 17:14
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册