发生了异常“Microsoft.VisualStudio.Debugger.Runtime.CrossThreadMessagingException”?

Nick_Ngai 2014-07-21 09:27:28
如题,并不会进入到catch,但是没有更新UI,不知道什么原因。
我的代码如下:
private void btnIPCrawl_Click(object sender, EventArgs e)
{
//隔段时间自动调用程序
System.Threading.Timer threadTimer = new System.Threading.Timer(new System.Threading.TimerCallback(InvokeIPCrawl), null, 0, 14400000);
while (true)
{
Thread.Sleep(14400000);
}
}

//分别调用抓取IP方法
private void InvokeIPCrawl(Object state)
{
SaveIPToDB(proxy360, "span");
}

/// <summary>
/// 将网络抓取的IP地址保存的数据库
/// </summary>
/// <param name="url">URL地址</param>
/// <param name="tagname">标签名称(不可为空)</param>
protected void SaveIPToDB(string url, string tagname)
{
try
{
string html = CUtils.GetHtmlSource(url);

Regex reg = CUtils.GetRegexIP(tagname);
if (reg != null)
{
CDatabase db = new CDatabase("phone");
try
{
MatchCollection mc = reg.Matches(html);
foreach (Match m in mc)
{
//抓取字符串中IP地址
MatchCollection submc = Regex.Matches(m.Groups[0].ToString(), @"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}");
foreach (Match item in submc)
{
if (CUtils.isIP(item.Groups[0].ToString()))
{
//插入数据库操作
string remark = "自动抓取的代理IP@" + url;
CDatabaseDAL.p_badagentip_insert(item.Groups[0].ToString(), remark, db);
count++;
this.BeginInvoke(new System.Threading.ThreadStart(delegate()
{
lblCount.Text = count.ToString();
}));
}
}
}
}
catch (Exception ex)
{ }
finally
{
db.close();
}
}
}
catch (Exception ex)
{ }
}
...全文
983 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
Nick_Ngai 2014-07-21
  • 打赏
  • 举报
回复
引用 2 楼 findcaiyzh 的回复:
线程里不能更新UI,得用委托 参考: How to update the GUI from another thread in C#? http://stackoverflow.com/questions/661561/how-to-update-the-gui-from-another-thread-in-c
那个方法好像不行的,导致我的程序不能循环操作,只执行一次就停掉了
引用 3 楼 findcaiyzh 的回复:
你在Timer里开了个线程,专门用于更新UI?有点奇怪,直接更新不行吗?
要求开个线程。另外要求每隔4小时调用一次程序。
宝_爸 2014-07-21
  • 打赏
  • 举报
回复
你在Timer里开了个线程,专门用于更新UI?有点奇怪,直接更新不行吗?
宝_爸 2014-07-21
  • 打赏
  • 举报
回复
线程里不能更新UI,得用委托 参考: How to update the GUI from another thread in C#? http://stackoverflow.com/questions/661561/how-to-update-the-gui-from-another-thread-in-c
Nick_Ngai 2014-07-21
  • 打赏
  • 举报
回复
this.BeginInvoke(new System.Threading.ThreadStart(delegate() { lblCount.Text = count.ToString(); })); 调试到这里看到的错误提示:不能进入 lblCount.Text = count.ToString();
Nick_Ngai 2014-07-21
  • 打赏
  • 举报
回复
已经解决了,原因是定时导致界面卡死。 将定时调用放到线程中就好了,修改代码如下: private void btnIPCrawl_Click(object sender, EventArgs e) { Thread thread = new Thread(TimerCrawlIP); thread.IsBackground = true; thread.Start(); } /// <summary> /// 定时抓取IP /// </summary> private void TimerCrawlIP() { //隔段时间自动调用程序 System.Threading.Timer threadTimer = new System.Threading.Timer(new System.Threading.TimerCallback(InvokeIPCrawl), null, 0, 14400000); while (true) { Thread.Sleep(14400000); } }

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧