提高UI响应速度


Windows窗体体系结构的约束:
不能在UI线程之外的其他线程(worker线程)调用UI的任何成员。

例如:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Test
{
    
public partial class Form1 : Form
    
{
        
public Form1()
        
{
            InitializeComponent();
        }

        
        
public delegate int OnAdd(int i, int j);

        
int Add(int m, int n)
        
{            
            
int sum = m + n;
            button1.Text 
= sum.ToString();

            
return sum;
        }


        
private void button1_Click(object sender, EventArgs e)
        
{
            OnAdd proc 
= Add;
            System.IAsyncResult async 
= proc.BeginInvoke(11nullnull);
            
// 下面两行等待proc完成,所以要想让界面有
            
// 反映(假设IntAdd需要花一些时间才能完成),还要注释掉它们。
            int sum = proc.EndInvoke(async);
            Console.WriteLine(sum);
        }

    }

}


“异步委托调用”通过线程池中的线程访问了button1.Text。于是出错了!

正确的更新UI方法:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Test
{
    
public partial class Form1 : Form
    
{
        
public Form1()
        
{
            InitializeComponent();
        }


        
public delegate int OnAdd(int i, int j);
        
public delegate void OnUpdateUI(object sender, string text);

        
int Add(int m, int n)
        
{
            
int sum = m + n;
            
//button1.Text = sum.ToString();
            object[] pList = this, sum.ToString() };
            button1.BeginInvoke(
new OnUpdateUI(UpdateUI), pList);

            
return sum;
        }


        
private void UpdateUI(object sender, string text)
        
{
            button1.Text 
= text;
        }


        
private void button1_Click(object sender, EventArgs e)
        
{
            OnAdd proc 
= Add;
            System.IAsyncResult async 
= proc.BeginInvoke(11nullnull);
            
// 下面两行等待proc完成,所以要想让界面有
            
// 反映(假设IntAdd需要花一些时间才能完成),还要注释掉它们。
            int sum = proc.EndInvoke(async);
            Console.WriteLine(sum);
        }

    }

}




http://www.microsoft.com/china/MSDN/library/enterprisedevelopment/softwaredev/misMultithreading.mspx?mfr=true






待续。。。




posted @ 2008-06-26 17:50  h2appy  阅读(254)  评论(0编辑  收藏  举报