C# 中和VB.NET 的异步方法和执行

发布日期:2021-05-24

 本文记录.NET 平台下VB.NET 和C#.NET下的各版本异步操作调用

1.C#中BeginInvoke


 

Func<string,int> CalcFunc = delegate (string para) {

                int count = 0;
                for (int i = 0; i < 1000000000; i++)
                {
                    count++;
                }
                return count;
            };

            CalcFunc.BeginInvoke("",(IAsyncResult result) => 
            {
                int count  = ((Func<string, int>)result.AsyncState).EndInvoke(result);
                this.txt_msg.Invoke((Action)(delegate () {
                    this.txt_msg.AppendText(count.ToString() + " ");
                    this.txt_msg.AppendText("循环计算完毕.".ToString() + " ");
                }));
            }, CalcFunc);

            this.txt_msg.AppendText("正在循环计算".ToString() + " ");



2.VB.NET 中 BeginInvoke

 

Dim CalcFunc As Func(Of String, Integer) = Sub(para As String) 
Dim count As Integer = 0
For i As Integer = 0 To 999999999
count += 1
Next
Return count

End Sub
CalcFunc.BeginInvoke("", Function(result As IAsyncResult) 
Dim count As Integer = DirectCast(result.AsyncState, Func(Of String, Integer)).EndInvoke(result)
Me.txt_msg.Invoke(DirectCast(Sub() 
Me.txt_msg.AppendText(count.ToString() + vbCr & vbLf)
Me.txt_msg.AppendText("循环计算完毕.".ToString() + vbCr & vbLf)

End Sub, Action))

End Function, CalcFunc)
Me.txt_msg.AppendText("正在循环计算".ToString() + vbCr & vbLf)

3.C#.NET 中 .NetFramework 4.5 以上的异步操作

 

 async Task<int> XunhuanAsync()
        {
            int count = 0;
           await  Task.Run(()=> 
            {
                for (int i = 0; i < 1000000000; i++)
                {

                    count++;
                }
            });
            return count;
        }

4.VB.NET 中 .NetFramework 4.5 以上的异步操作

Private Function XunhuanAsync() As Task(Of Integer)
Dim count As Integer = 0
Await Task.Run(Function() 
For i As Integer = 0 To 999999999
count += 1
Next

End Function)
Return count
End Function

5.C#.NET 中 .NetFramework 3.5 以下的异步操作


  

private delegate  int BeginInvokeMehtod();

 int BeginXunHuan()
        {
            int count = 0;

            for (int i = 0; i < 1000000000; i++)
            {

                count++;
            }
            return count;
        }

 void XunHuanCallbak(IAsyncResult result)
        {
            try
            {
               
                int count = ((BeginInvokeMehtod)result.AsyncState).EndInvoke(result);
                this.txt_msg.Invoke((Action)(delegate () {
                    this.txt_msg.AppendText(count.ToString() + " ");
                    this.txt_msg.AppendText("循环计算完毕.".ToString() + " ");
                }));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
             
        } 




  BeginInvokeMehtod xunhuan = new BeginInvokeMehtod(BeginXunHuan);
  xunhuan.BeginInvoke(XunHuanCallbak, xunhuan);