EF 在表中插入值在一段时间后失败



我正在研究EF.我正在尝试插入到表中,插入功能在线程中。

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
int bytes = port.BytesToRead;
//string indata = sp.ReadExisting();
Thread.Sleep(50);
try
{
receivedBytes = port.BaseStream.Read(buffer, 0, (int)buffer.Length);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
var receiveData = BitConverter.ToString(buffer, 0, receivedBytes);
var finalData = receiveData.Replace("-", "");
//Thread.Sleep(100);
Console.WriteLine("Thread Going to Start");
new Thread(() => {
SaveData(finalData);
}).Start(); // starting the thread
port.DiscardOutBuffer(); 
port.DiscardInBuffer();
}

这是我的保存数据功能

public void SaveData(string finalData)
{
Console.WriteLine(LineNumber() + "Data Transmiting...");
thread = Thread.CurrentThread;         

mdc_dbEntities e = new mdc_dbEntities();
var msn = e.mdc_meter_config.Where(m => m.m_hex == sr).Select(s => new { s.msn, s.p_id, s.meter_id }).ToList();
var H = finalData.Substring(0, 2);
using (mdc_dbEntities u = new mdc_dbEntities())
{
foreach (var res in msn)
{
var cust_id = e.mdc_meter_cust_rel.Where(m => m.msn == res.msn)
.Select(s => s.cust_id)
.FirstOrDefault();
mdc_meters_data data = new mdc_meters_data()
{
msn = res.msn,
cust_id = cust_id,
device_id = res.meter_id.ToString(),
kwh = e_val.ToString(),
voltage_p1 = a_vol_val.ToString(),
voltage_p2 = b_vol_val.ToString(),
voltage_p3 = c_vol_val.ToString(),
current_p1 = a_curr_val.ToString(),
current_p2 = b_curr_val.ToString(),
current_p3 = c_curr_val.ToString(),
data_date_time = Convert.ToDateTime(theDate.ToString(format)),
d_type = d_type.ToString(),
pf1 = a_pf_val.ToString(),
pf2 = b_pf_val.ToString(),
pf3 = c_pf_val.ToString(),
p_id = res.p_id,
};
u.mdc_meters_data.Add(data);
}
u.SaveChanges();
}
Console.WriteLine(LineNumber() + "Data Saved");
Thread.Sleep(50);
}
try
{
thread.Abort(); // aborting it after insertion
//Thread.Sleep(50);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}

上面的代码运行了一段时间,但之后我在u.SaveChanges();

System.Data.Entity.Core.EntityException:"关闭提供程序连接时出错。有关详细信息,请参阅内部例外。

MySqlException:命令执行期间遇到的致命错误。
MySql异常:尝试读取结果集时遇到致命错误。
MySqlException:从流读取失败。

IOException:无法从传输连接读取数据:连接尝试失败,因为连接方在一段时间后未正确响应,或者建立的连接失败,因为连接的主机无法响应。

套接字异常:连接尝试失败,因为连接方在一段时间后未正确响应,或建立的连接失败,因为连接的主机无法响应

我已经研究了每个解决方案并尝试了它们,但仍然无法解决此问题。我一定错过了一些我不知道的东西。

更新 1 我的整个代码

调用构造函数

public CommunicationEngine()
{
port.ReadTimeout = 500;
port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
port.Open();
Console.WriteLine("Port opened successfully");
Console.WriteLine("I am Recieving");
}

调用处理程序

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
int bytes = port.BytesToRead;

Thread.Sleep(50);
Console.WriteLine("Bytes are ok..." + port.BytesToRead + " Recieved ");
try
{
receivedBytes = port.BaseStream.Read(buffer, 0, (int)buffer.Length);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}

var receiveData = BitConverter.ToString(buffer, 0, receivedBytes);
var finalData = receiveData.Replace("-", "");
//Thread.Sleep(100);
Console.WriteLine("Thread Going to Start");
try
{
new Thread(() => {
SaveData(finalData);
}).Start();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}          

port.DiscardOutBuffer(); port.DiscardInBuffer();

}

将数据保存到数据库中

public void SaveData(string finalData)
{
Console.WriteLine(LineNumber() + "Data Transmiting...");
thread = Thread.CurrentThread;
if (finalData.Length == 138)
{
comm = true;
var H = finalData.Substring(0, 2);
var FC = finalData.Substring(2, 9);
var len = finalData.Substring(10, 2);
var sr = finalData.Substring(12, 12);
var energy_tag = finalData.Substring(24, 4);
var e_val = hexToDec(finalData.Substring(28, 8)) / 10;
var a_curr_tag = finalData.Substring(36, 4);
var a_curr_val = hexToDec(finalData.Substring(40, 8)) / 1000;
var b_curr_tag = finalData.Substring(48, 4);
var b_curr_val = hexToDec(finalData.Substring(52, 8)) / 1000;
var c_curr_tag = finalData.Substring(60, 4);
var c_curr_val = hexToDec(finalData.Substring(64, 8)) / 1000;
var a_vol_tag = finalData.Substring(72, 4);
var a_vol_val = hexToDec(finalData.Substring(76, 8)) / 10;
var b_vol_tag = finalData.Substring(84, 4);
var b_vol_val = hexToDec(finalData.Substring(88, 8)) / 10;
var c_vol_tag = finalData.Substring(96, 4);
var c_vol_val = hexToDec(finalData.Substring(100, 8)) / 10;
var a_pf_tag = finalData.Substring(108, 4);
var a_pf_val = hexToDec(finalData.Substring(112, 4)) / 1000;
var b_pf_tag = finalData.Substring(116, 4);
var b_pf_val = hexToDec(finalData.Substring(120, 4)) / 1000;
var c_pf_tag = finalData.Substring(124, 4);
var c_pf_val = hexToDec(finalData.Substring(128, 4)) / 1000;
var crc = finalData.Substring(132, 4);
var ftr = finalData.Substring(136, 2);

var d_type = "600";
DateTime theDate = DateTime.Now;
string format = "yyyy-MM-dd HH:mm:ss";
Console.WriteLine(LineNumber() + "Data Ready to be inserted in DB");
using (mdc_dbEntities u = new mdc_dbEntities())
{
var msnList = u.mdc_meter_config.Where(m => m.m_hex == sr)
.Select(s => new { s.msn, s.p_id, s.meter_id })
.ToList();
foreach (var res in msnList)
{
var cust_id = u.mdc_meter_cust_rel.Where(m => m.msn == res.msn)
.Select(s => s.cust_id)
.FirstOrDefault();
mdc_meters_data data = new mdc_meters_data()
{
msn = res.msn,
cust_id = cust_id,
device_id = res.meter_id.ToString(),
kwh = e_val.ToString(),
voltage_p1 = a_vol_val.ToString(),
voltage_p2 = b_vol_val.ToString(),
voltage_p3 = c_vol_val.ToString(),
current_p1 = a_curr_val.ToString(),
current_p2 = b_curr_val.ToString(),
current_p3 = c_curr_val.ToString(),
data_date_time = Convert.ToDateTime(theDate.ToString(format)),
d_type = d_type.ToString(),
pf1 = a_pf_val.ToString(),
pf2 = b_pf_val.ToString(),
pf3 = c_pf_val.ToString(),
p_id = res.p_id,
};
u.mdc_meters_data.Add(data);
}
try
{
u.SaveChanges();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}                
Console.WriteLine(LineNumber() + "Data Saved");
Thread.Sleep(50);
}
else if(finalData.Length == 30)
{
var msn_no = finalData.Substring(12, 12);
mdc_dbEntities p = new mdc_dbEntities();
var update = p.meter_control.Where(c => (c.comm_executed == 0))
.Where(o => (o.m_hex == msn_no))
.SingleOrDefault();
if(update.comm_sent == "Disconnect")
{
update.comm_executed = 1;
update.comm = 0;
p.SaveChanges();
Console.WriteLine("Meter Disconnected....");
}
else if(update.comm_sent == "Connect")
{
update.comm_executed = 1;
update.comm = 1;
p.SaveChanges();
Console.WriteLine("Meter Connected....");
}             
comm = true;
}
else
{
comm = true;
}
try
{
thread.Abort();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}

任何帮助将不胜感激。

在手动启动的线程中执行与 EF 相关的更改不是一个好主意。尝试在同一线程中运行 EF 更改。如果您在处理传入请求时遇到麻烦,请使用异步和等待功能。我已经修改了您的代码以适应此功能。请尝试此。

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
int bytes = port.BytesToRead;
//string indata = sp.ReadExisting();
try
{
receivedBytes = port.BaseStream.Read(buffer, 0, (int)buffer.Length);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
var receiveData = BitConverter.ToString(buffer, 0, receivedBytes);
var finalData = receiveData.Replace("-", "");
Console.WriteLine("Thread Going to Start");
SaveDataAsync(finalData).Wait(); // this call will become sync and runs under main thread.
port.DiscardOutBuffer(); 
port.DiscardInBuffer();
}
public async Task<bool> SaveDataAsync(string finalData)
{
mdc_dbEntities e = new mdc_dbEntities();
var msn = e.mdc_meter_config.Where(m => m.m_hex == sr).Select(s => new { s.msn, s.p_id, s.meter_id }).ToList();
var H = finalData.Substring(0, 2);
var isSaveSuccess = false;
using (mdc_dbEntities u = new mdc_dbEntities())
{
foreach (var res in msn)
{
var cust_id = e.mdc_meter_cust_rel.Where(m => m.msn == res.msn)
.Select(s => s.cust_id)
.FirstOrDefault();
mdc_meters_data data = new mdc_meters_data()
{
msn = res.msn,
cust_id = cust_id,
device_id = res.meter_id.ToString(),
kwh = e_val.ToString(),
voltage_p1 = a_vol_val.ToString(),
voltage_p2 = b_vol_val.ToString(),
voltage_p3 = c_vol_val.ToString(),
current_p1 = a_curr_val.ToString(),
current_p2 = b_curr_val.ToString(),
current_p3 = c_curr_val.ToString(),
data_date_time = Convert.ToDateTime(theDate.ToString(format)),
d_type = d_type.ToString(),
pf1 = a_pf_val.ToString(),
pf2 = b_pf_val.ToString(),
pf3 = c_pf_val.ToString(),
p_id = res.p_id,
};
u.mdc_meters_data.Add(data);
}
isSaveSuccess = (await u.SaveChangesAsync())>0; // if records inserted, the count will be more than 0
}
return isSaveSuccess;
}
}

这更容易阅读,可能会有所帮助

说了这么多,请确保你实际上可以连接到数据库 仔细检查连接字符串

public void SaveData(string finalData)
{
Console.WriteLine(LineNumber() + "Data Transmiting...");
using (mdc_dbEntities dbContext = new mdc_dbEntities())
{
var msnList = dbContext.mdc_meter_config.Where(m => m.m_hex == sr)
.Select(s => new { s.msn, s.p_id, s.meter_id })
.ToList();
//put debug point here and check that msnList is populated
foreach (var item in msnList)
{
//this is slow as it will be a db query for each loop
var cust_id = dbContext.mdc_meter_cust_rel.Where(m => m.msn == item.msn)
.Select(s => s.cust_id)
.FirstOrDefault();
var data = new mdc_meters_data()
{
msn = item.msn,
cust_id = cust_id,
device_id = item.meter_id.ToString(),
kwh = e_val.ToString(),
voltage_p1 = a_vol_val.ToString(),
voltage_p2 = b_vol_val.ToString(),
voltage_p3 = c_vol_val.ToString(),
current_p1 = a_curr_val.ToString(),
current_p2 = b_curr_val.ToString(),
current_p3 = c_curr_val.ToString(),
data_date_time = Convert.ToDateTime(theDate.ToString(format)),
d_type = d_type.ToString(),
pf1 = a_pf_val.ToString(),
pf2 = b_pf_val.ToString(),
pf3 = c_pf_val.ToString(),
p_id = item.p_id,
};
dbContext.mdc_meters_data.Add(data);
}
//depending on how many you added this may take some time.
dbContext.SaveChanges();
}
}

相关内容

  • 没有找到相关文章

最新更新