在C# Winfrom项目中,利用Timer控件每隔1秒钟从TextBox文本框中获取数据。
目前文本框的数据可以获取到,不过在Debug调试代码时发现在断点到文本框获取值时报如下错误:
txtInputInfo.Text “txtInputInfo.Text”引发了“Microsoft.VisualStudio.Debugger.Runtime.CrossThreadMessagingException”类型的异常 string {Microsoft.VisualStudio.Debugger.Runtime.CrossThreadMessagingException}
其中txtInputInfo为文本框的ID,请问如何解决。谢谢!
代码如下:
private void timer1_Tick(object sender, EventArgs e)
{
try
{
run();
}
catch (Exception ex)
{
CLog.Log(string.Format("timer1_Tick:{0}\terrmsg:{1}", this.ToString(), ex.Message));
}
}
void run()
{
Thread thread = new Thread(new ThreadStart(doListening)); thread.Start();
}
void doListening()
{
try {
if (txtInputInfo.Text.Trim() != "" && txtInputInfo.Text.Trim() != tmpStr) //debug到这边获取文本框的值时,报上面的错误
{
if (txtInputInfo.Text.Trim().StartsWith("<s>") && txtInputInfo.Text.Trim().EndsWith("<e>"))
{
string[] s = GetInputInfo(txtInputInfo.Text.Trim().Replace("<s>", "").Replace("<e>", ""));
tax.buyeropeningname = s[0];
tax.buyertaxpayernumber = s[1];
tax.buyeraddressphone = s[2];
tax.buyerbankaccount = s[3];
System.Threading.Thread.Sleep(20);
m_trdWindow = new CTrdScanningWindow(TARGET_SUB_CLASS_NAME, TARGET_CLASS_NAME, ClientIni.GetWinApply("TARGET_Panel_NAME"), ClientIni.GetWinApply("TARGET_MAIN_NAME"), tax); System.Threading.Thread.Sleep(20);
Clear();
}
}
}
catch(Exception ex){
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
跨线程操作了
怎么改,谢谢
@lwr: 你将获取文本框内容单独写方法:
/// <summary>
/// 获取文本框文本委托
/// </summary>
/// <param name="Ctrl"></param>
private delegate string GetTextBoxTextDelegate(TextBox Ctrl);
/// <summary>
/// 获取文本框文本方法
/// </summary>
/// <param name="Ctrl"></param>
private static string GetTextBoxTextFunc(TextBox Ctrl)
{
return Ctrl.Text;
}
/// <summary>
/// 获取文本框文本
/// </summary>
/// <param name="Ctrl"></param>
/// <returns></returns>
public static string GetTextBoxText(TextBox Ctrl)
{
return (string)Ctrl.Invoke(new GetTextBoxTextDelegate(GetTextBoxTextFunc), new object[] { Ctrl });
}
使用:
var str = GetTextBoxText(txtInputInfo);
可以看下这个:WinForm跨线程UI操作常用控件类大全
异常已经很清楚了,查就查,开什么线程(这点查询还会卡起?),开线程又乱用,Invoke
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;