lijinchang

导航

利用委托的BeginInvoke防止界面假死的实例

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 WinBeginInvoke
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private delegate int Mydelegate();
        private int Method()
        {
            Thread.Sleep(10000);
            Random rad = new Random();
            int i = rad.Next(1000);
            return i;
        }

        private void MyMethodComplete(IAsyncResult asyncresult)
        {
            if (asyncresult == null)
                return;
            textBox1.Text = (asyncresult.AsyncState as Mydelegate).EndInvoke(asyncresult).ToString() ;
            button1.Enabled = true;
         
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Mydelegate my = Method;
            button1.Enabled = false;
            IAsyncResult result= my.BeginInvoke(MyMethodComplete, my);
            if (!result.IsCompleted)
            {
           
           
            }
           
        }
    }
}

posted on 2011-05-03 16:47  lijinchang  阅读(412)  评论(0编辑  收藏  举报