C# 未在mscorlib.dll中处理System.Reflection.TargetInvocationException异常
我试图从数字万用表中读取串行数据,我认为数据偶尔会被破坏。大约95%的时间我可以读取数据并将其显示在文本框中,但偶尔会出现以下错误: 在mscorlib.dll中未处理System.Reflection.TargetInvocationException异常 InnerException是:Message=输入字符串的格式不正确 我不熟悉Windows WPF和C#编程,但我认为这意味着接收到的数据没有正确终止 下面是我的Receive()代码: 处理损坏数据的正确方法是什么 更新:这是我的writeData():C# 未在mscorlib.dll中处理System.Reflection.TargetInvocationException异常,c#,wpf,C#,Wpf,我试图从数字万用表中读取串行数据,我认为数据偶尔会被破坏。大约95%的时间我可以读取数据并将其显示在文本框中,但偶尔会出现以下错误: 在mscorlib.dll中未处理System.Reflection.TargetInvocationException异常 InnerException是:Message=输入字符串的格式不正确 我不熟悉Windows WPF和C#编程,但我认为这意味着接收到的数据没有正确终止 下面是我的Receive()代码: 处理损坏数据的正确方法是什么 更新:这是我的wr
不一定,这可能意味着您有一个格式无效的something
.Parse
。你能把代码显示在你使用数据的地方吗?或者这是某个控件上的数据绑定?如果是,请显示绑定。问题似乎出在WriteData方法内部。这是你实施的方法吗?如果是,请也发送该方法。好吧,与“未正确终止”无关,否则ReadLine()将无法完成。您需要添加日志记录,以便记录得到的坏字符串,在catch{}中这样做。您需要实现ErrorReceived事件处理程序,以便知道您遇到了错误。在所有可能的情况下,我强烈建议您始终使用TryParse而不是Parse。有点认为微软应该禁止解析API。同意@Hans Passant。你需要放置一个记录器来判断出什么地方出了问题。像myTextStripped/myText这样的东西在代码中没有基本的验证或登录。当意外的事情发生时,有点难说到底出了什么问题。
private delegate void UpdateUiTextDelegate(string text);
private void Recieve(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
// Collecting the characters received to our 'buffer' (string).
received_data = serial.ReadLine();
Dispatcher.Invoke(DispatcherPriority.Send, new UpdateUiTextDelegate(WriteData), received_data);
}
private void WriteData(string text)
{
string myTextStripped;
string avgText;
string textChar;
string currentFilteredText;
double current;
double difference;
int range;
textBox2.Text = myText; // display raw string data
myTextStripped = text.Substring(1, 7); // remove chars after 7th char
myTextStrippedTextBox.Text = myTextStripped; // display trimmed string
if (myTextStripped[5] == '2') // range 0 - 59.9 mV
{
range = 1;
myTextStripped = myText.Remove(4); // keep first 4 chars
current = float.Parse(myTextStripped);
current = current / 100;
myTextStrippedTextBox.Background = Brushes.Yellow;
}
else if (myTextStripped[5] == '3') // range is 60mV - 600mV
{
range = 2;
myTextStripped = myText.Remove(4); // keep first 4 chars
current = float.Parse(myTextStripped);
current = current / 10;
myTextStrippedTextBox.Background = Brushes.YellowGreen;
}
else // range is 600mv+
{
range = 3;
myTextStripped = myText.Remove(4); // keep first 4 chars
current = float.Parse(myTextStripped);
myTextStrippedTextBox.Background = Brushes.PaleVioletRed;
}
// Filter results because readings jump too much to visually determine a good value
difference = (current - currentFiltered);
currentFiltered = currentFiltered + (filterFactor * difference);
avgText = currentFiltered.ToString(".000");
avgText = avgText.TrimStart('0');
currentTextBox.Text = avgText;
}