当前位置:编程学习 > asp >>

使用委托的BeginInvoke方法来完成复杂任务的操作

 现在假设我有这样一个窗体(包含一个进度条和一个按钮与两个文本框),在第一个文本框中输入一个数字进行阶乘运算,在此过程中进度条与运算进度保持一致,同时可以在第二个文本框中进行其它工作(比如输入)。对付这样的题目,除了使用BackGroundWorker之外还可以使用异步Invoke来完成:
首先让我们看看界面以及对应的代码:
【界面】

【代码】

[C#]
namespace CSharp
{
    public partial class Form1 : Form
    {
        long result = 1;

         long PGo(int endnum)
        {
            while(progressBar1.Value<=endnum)
            {
                result *= endnum;
                progressBar1.Value += 1;
                Thread.Sleep(1000);
                endnum--;
            }
            return result;
        }

        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
           
        }

        private void button1_Click(object sender, EventArgs e)
        {
            progressBar1.Maximum = Convert.ToInt32(textBox1.Text);
            Func<int,long> a = new Func<int,long>(PGo);

            //BeginInvoke先启动后台线程做循环
            var result = a.BeginInvoke
                (
                Convert.ToInt32(textBox1.Text),
                //如果完成了循环,那么执行此委托
                    delegate(IAsyncResult r)
                    {
                        if (r.IsCompleted)
                        {
                            MessageBox.Show("Finished!");
                            textBox1.Text = (r.AsyncState as Func<int, long>).EndInvoke(r).ToString();
                        }
                    },a
                );

            //不能使用result.EndInvoke,此方法将导致当前进程宕住,直到后台线程完毕为止。因为WinForm主线程不会自动关闭,所以
            //无需此线程,但是控制台程序必须要!因为控制台进程“瞬间即逝”。
        }
    }
}
[VB.NET]
Namespace CSharp
    Public Partial Class Form1
        Inherits Form
        Private result As Long = 1

        Private Function PGo(endnum As Integer) As Long
            While progressBar1.Value <= endnum
                result *= endnum
                progressBar1.Value += 1
                Thread.Sleep(1000)
                endnum -= 1
            End While
            Return result
        End Function

        Public Sub New()
            InitializeComponent()
        End Sub
        Private Sub Form1_Load(sender As Object, e As EventArgs)

        End Sub

        Private Sub button1_Click(sender As Object, e As EventArgs)
            progressBar1.Maximum = Convert.ToInt32(textBox1.Text)
            Dim a As New Func(Of Integer, Long)(AddressOf PGo)

            'BeginInvoke先启动后台线程做循环
            '如果完成了循环,那么执行此委托 www.zzzyk.com
            Dim result = a.BeginInvoke(Convert.ToInt32(textBox1.Text), Function(r As IAsyncResult) Do
                If r.IsCompleted Then
                    MessageBox.Show("Finished!")
                    textBox1.Text = TryCast(r.AsyncState, Func(Of Integer, Long)).EndInvoke(r).ToString()
                End If
            End Function, a)
            '不能使用result.EndIn

补充:Web开发 , ASP.Net ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,