我在嘗試讓藍芽斷電,程式自動判斷斷線並重連,然後重連的速度非常的慢,平均20幾秒,請問有沒有辦法可以快一點,請各位大大給點建議,謝謝!(新手發問請見諒)。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using System.Diagnostics;
using System.Threading;
namespace SkillsTestCode
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Stopwatch stopwatch = new Stopwatch();
SerialPort port = new SerialPort();
delegate void abc();
byte[] data = new byte[4];
bool Flag_Send = false, Flag_Link_Connect = false, Flag_Link_Com = true, abcd = true;
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = DateTime.Now.ToString("hh:mm:ss");
}
private void timer2_Tick(object sender, EventArgs e)
{
if (Flag_Link_Com)
{
if (port.BytesToRead > 0)
{
try
{
port.ReadTimeout = 100;
data[0] = (byte)port.ReadByte();
port.DiscardInBuffer();
if (data[0] == 0xFF)
{
Flag_Send = true;
Flag_Link_Connect = true;
}
}
catch (Exception) { Console.WriteLine("讀取逾時!"); }
}
if (Flag_Send)
{
try
{
port.WriteTimeout = 100;
data[0] = 0xFF;
port.Write(data, 0, 1);
port.DiscardOutBuffer();
Flag_Link_Connect = true;
Flag_Send = false;
}
catch (Exception) { Console.WriteLine("傳送逾時!"); }
}
if (Flag_Link_Connect)
{
Flag_Link_Connect = false;
}
else
{
port.Close();
stopwatch.Restart();
stopwatch.Start();
LableText(false);
button1.Text = "OPEN";
Flag_Link_Com = false;
}
}
else
{
if (abcd)
{
abcd = false;
Task.Run(() =>
{
try
{
Task.Delay(1000).Wait();
Console.WriteLine(Task.CurrentId + "-----OPEN oao");
port.Open();
stopwatch.Stop();
Console.WriteLine(Task.CurrentId + "----fuck-----" + stopwatch.ElapsedMilliseconds);
data[0] = 0xFF;
port.Write(data, 0, 1);
Flag_Link_Com = true;
this.Invoke(new abc(() =>
{
button1.Text = "CLOSE";
timer2.Enabled = true;
LableText(true);
}));
}
catch (Exception exx)
{
Console.WriteLine("--------------" + exx);
}
abcd = true;
});
}
}
}
private void comboBox1_DropDown(object sender, EventArgs e)
{
string[] PN = SerialPort.GetPortNames();
comboBox1.Items.Clear();
comboBox1.Items.AddRange(PN);
}
private void button1_Click(object sender, EventArgs e)
{
if (!port.IsOpen)
{
port.PortName = comboBox1.Text;
Task.Run(() =>
{
try
{
port.Open();
data[0] = 0xFF;
port.Write(data, 0, 1);
this.Invoke(new abc(() =>
{
timer2.Enabled = true;
button1.Text = "CLOSE";
LableText(true);
}));
}
catch (Exception) { };
});
}
else
{
timer2.Enabled = false;
port.Close();
LableText(false);
button1.Text = "OPEN";
}
}
void LableText(bool a)
{
if (a)
{
label2.Text = "ONLINE";
label2.BackColor = Color.Green;
}
else
{
label2.Text = "OFFLINE";
label2.BackColor = Color.Red;
}
}
}
}