这个系列从2009年写到2010年,差点又成太监文。随着WPF/Silverlight的袭来,WinForm慢慢的在灭迹,为了纪念我那两年多来开发WinForm的日子,遂撰写此系列,计划包括十篇文章,将我觉得WinForm开发需要注意的一些方面谈谈,前两篇已经写了(实际已经写了三篇),这是本系列第三篇:
WinForm二三事(三)Control.Invoke&Control.BeginInvoke
WinForm二三事(四)界面布局
WinForm二三事(五)实作
WinForm二三事(六)数据绑定
WinForm二三事(七)GDI+
WinForm二三事(八)开源项目
WinForm二三事(九)常用第三方控件库
WinForm二三事(十)漫谈
从异常开始
在上一篇文章中,为了提高用户体验,使用delegate构造一个异步操作,但是在这个异步操作里操作UI控件的属性的时候却发生异常。实际上使用delegate构造异步操作这种方式,在背后还是创建了一个worker thread,从不是创建UI的thread里去操作UI元素的属性就会抛出这个异常。
不过,如果我们不在Visual Studio里运行这个程序,直接运行,这个异常却不会出现。通过查看异常的StackTrace,发现该异常是在获取Control的句柄时抛出的:
at System.Windows.Forms.Control.get_Handle()
at System.Windows.Forms.Control.set_WindowText(String value)
at System.Windows.Forms.Control.set_Text(String value)
at System.Windows.Forms.ButtonBase.set_Text(String value)
//..省略...
祭出Reflector,看看相关代码:
2: {
3: get
4: {
this.InvokeRequired)
6: {
this.Name }));
8: }
this.IsHandleCreated)
10: {
this.CreateHandle();
12: }
this.HandleInternal;
14: }
15: }