我正在编写一个类库,它使用串行端口通过专有协议从设备传输数据。
当我用作Windows窗体应用程序时它工作正常。当我将它转换为类lib时,它在处理第一位数据后结束。是否需要进行一些线程以防止将其返回到调用它的应用程序?它需要确保在将控制权返回给调用它的应用程序之前收集了设备中的所有数据。
以下是早期结束的完整代码:
using System;
using System.Text;
using System.IO.Ports;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Runtime.InteropServices;
namespace ValidataDex
{
public class DexLib
{
public Crc16 c = new Crc16();
public Search s = new Search();
const ushort polynomial = 0xA001;
ushort[] table = new ushort[256];
SerialPort port = null; // create port so it can be used and seen everywhere
int good = 0; // is dex good
public string myblock;
public delegate void SetTextDeleg(byte[] text);
public int count;
public string stage = "initial";
public string position = "";
public string crcstuff = "";
public byte[] crcdata;
public int lastsent = 0;
public int audit = 0;
public char etboretx;
public int gotenq = 0;
public int x = 2;
public int positiondetermined = 0;
// Dex Commands
public byte NUL = 0x00;
public byte SOH = 0x01;
public byte STX = 0x02;
public byte ETX = 0x03;
public byte EOT = 0x04;
public byte ENQ = 0x05;
public byte ACK = 0x06;
public byte DLE = 0x10;
public byte NAK = 0x15;
public byte SYN = 0x16;
public byte ETB = 0x17;
public string Dex;
public int rte=0;
public string CHANGER_IS_SLAVE = "9252130100RR01L01";
byte zero = 0x30;
byte one = 0x31;
public void Data_Received(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
count = port.BytesToRead;
byte[] data = new byte[count];
port.Read(data, 0, data.Length);
// audit function activated by a file named debug residing in application directory
string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
if (audit == 1 || File.Exists(path + @"\debug.txt"))
{
x = 0;
foreach (byte b in data)
{
audit_file(1, "stage:"+stage+" command:"+getdexcommand(b)+" pos det:"+positiondetermined);
// textBox1.Text += getdexcommand(b);
x++;
}
}
try
{
// wait for device to transmit a DLE to begin DEX
if (data[0] == DLE || positiondetermined == 1)
{
DexasMaster(data);
}
}
catch (Exception ee)
{
audit_file(2, ee.InnerException.ToString());
}
}
答案 0 :(得分:0)
答案是提供一个Thread.Sleep足够长的时间来处理所有数据。之后,它就像一个魅力。