一个关于异步调用+多线程+异常处理的问题,请高手帮忙!!!
我在WinForm里加了如下引用:
using System.Threading;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Reflection;
using System.Runtime.CompilerServices;
声明了以下变量:
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button1;
private int count = 0;
private delegate void AddMessageHandler(string msg);
private AddMessageHandler addMsgHandler;
private AsyncCallback addCallback;
private System.Windows.Forms.Timer timer1;//timer1的时间间隔是一秒
private System.ComponentModel.IContainer components;
private string[] hehe = new string[3]{"first","second","third"};
定义了如下方法:
public Form1()
{
InitializeComponent();
//指定代理调用的方法
addMsgHandler = new AddMessageHandler(AddMsg);
//指定回调的方法
addCallback = new AsyncCallback(EndMsg);
}
private void button1_Click(object sender, System.EventArgs e)
{
this.count = 0;
//timer启动一个线程
this.timer1.Start();
}
private void add(object hehe)
{
this.timer1.Stop();
string[] thishehe = (string[])hehe;
try
{
this.timer1.Start();
IAsyncResult ar = addMsgHandler.BeginInvoke(thishehe[count],addCallback,null);
}
catch(IndexOutOfRangeException E) //获得异常
{
Console.WriteLine("exception at :{0},{1}",DateTime.Now.Ticks,count);
this.timer1.Stop();
IAsyncResult ar = addMsgHandler.BeginInvoke(E.Message,addCallback,null);
}
count++;
}
private void AddMsg(string msg)
{
this.textBox1.Text = msg;
}
private void EndMsg(IAsyncResult ar)
{
AddMessageHandler tempMessageHandler = (AddMessageHandler)((AsyncResult)ar).AsyncDelegate;
Console.WriteLine(DateTime.Now);
tempMessageHandler.EndInvoke(ar);
}
private void timer1_Tick(object sender, System.EventArgs e)
{
//timer1的时间间隔是一秒
this.add(this.hehe);
}
由于程序是多线程的,又是异步调用的,所以timer1_Tick触发的方法改变this.textBox1的text是不会受到后台的影响的,但程序运行结果不是这样:
在显示first和second时的确可以随意拖动WinForm,程序不受后台处理的影响,可以证明是异步的,
但当catch(IndexOutOfRangeException E)获得异常时,即显示third后WinForm窗体不能拖动,有同步执行的感觉,感觉是等处理完了IndexOutOfRangeException E才回到WinForm,查看输出,发现这时加载了已加载“c:\winnt\assembly\gac\mscorlib.resources\1.0.5000.0_zh-chs_b77a5c561934e089\mscorlib.resources.dll”,未加载符号。
我是Win2000Server的系统
查c:\winnt\assembly\下的确有mscorlib.resources这个程序集的映射,但找不到mscorlib.resources.dll
想利用mscorlib.dll里的Assembly.Load方法来自己加载这个程序集,但是失败,望高手指点为什么会出现这样的情况?
是由于程序在load mscorlib.resources时所有的线程都会挂起等待吗????
有什么解决办法呢?