现在的位置: 首页 > 综合 > 正文

BeginInvoke和EndInvoke方法

2013年09月11日 ⁄ 综合 ⁄ 共 7890字 ⁄ 字号 评论关闭

开发语言:
C#3.0

IDE
Visual Studio 2008

本系列教程主要包括如下内容:

1.  BeginInvoke

EndInvoke方法

2.  Thread

3. 线程池

4. 线程同步基础

5. 死锁

6. 线程同步的
7种方法

7. 如何在线程中访问
GUI组件

一、线程概述

在操作系统中一个进程至少要包含一个线程,然后,在某些时候需要在同一个进程中同时执行多项任务,或是为了提供程序的性能,将要执行的任务分解成多个子任务执行。这就需要在同一个进程中开启多个线程。我们使用
C#
编写一个应用程序(控制台或桌面程序都可以),然后运行这个程序,并打开
windows
任务管理器,这时我们就会看到这个应用程序中所含有的线程数,如下图所示。

<!--
/* Font Definitions */
&#64;font-face
{font-family:宋体;
panose-1:2 1 6 0 3 1 1 1 1 1;}
&#64;font-face
{font-family:""&#64;宋体";
panose-1:2 1 6 0 3 1 1 1 1 1;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
text-align:justify;
text-justify:inter-ideograph;
font-size:10.5pt;
font-family:"Times New Roman";}
/* Page Definitions */
&#64;page
{}
&#64;page Section1
{size:612.0pt 792.0pt;
margin:72.0pt 90.0pt 72.0pt 90.0pt;}
div.Section1
{page:Section1;}
-->

如果任务管理器没有“线程数”列,可以【查看】
>【选择列】来显示“线程计数”列。从上图可以看出,几乎所有的进程都拥有两个以上的线程。从而可以看出,线程是提供应用程序性能的重要手段之一,尤其在多核
CPU的机器上尤为明显。


二、用委托
(Delegate)


BeginInvoke


EndInvoke

方法操作线程

 


C#中使用线程的方法很多,使用委托的
BeginInvoke
EndInvoke方法就是其中之一。
BeginInvoke方法可以使用线程异步地执行委托所指向的方法。然后通过
EndInvoke方法获得方法的返回值(
EndInvoke方法的返回值就是被调用方法的返回值),或是确定方法已经被成功调用。我们可以通过四种方法从
EndInvoke方法来获得返回值。

三、直接使用
EndInvoke

方法来获得返回值

   
当使用
BeginInvoke
异步调用方法时,如果方法未执行完,
EndInvoke
方法就会一直阻塞,直到被调用的方法执行完毕。如下面的代码所示:

using
 System;

using
 System.Collections.Generic;

using
 System.Linq;

using
 System.Text;

using
 System.Threading;


namespace
 MyThread
{
    

class
 Program
    {
        

private
 
static
 
int
 newTask(
int
 ms)
        {
            Console.WriteLine(

"
任务开始
"
);
            Thread.Sleep(ms);
            Random random 

=
 
new
 Random();
            

int
 n 
=
 random.Next(
10000
);
            Console.WriteLine(

"
任务完成
"
);
            

return
 n;
        }

        
private
 
delegate
 
int
 NewTaskDelegate(
int
 ms);
             
        
        

static
 
void
 Main(
string
[] args)
        {
            NewTaskDelegate task 

=
 newTask;
            IAsyncResult asyncResult 

=
 task.BeginInvoke(
2000

null

null
);


            //
 EndInvoke方法将被阻塞2秒


            
int
 result 
=
 task.EndInvoke(asyncResult);           
            Console.WriteLine(result);
        }
    }
}

<!--
/* Font Definitions */
&#64;font-face
{font-family:宋体;
panose-1:2 1 6 0 3 1 1 1 1 1;}
&#64;font-face
{font-family:""&#64;宋体";
panose-1:2 1 6 0 3 1 1 1 1 1;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
text-align:justify;
text-justify:inter-ideograph;
font-size:10.5pt;
font-family:"Times New Roman";}
/* Page Definitions */
&#64;page
{}
&#64;page Section1
{size:612.0pt 792.0pt;
margin:72.0pt 90.0pt 72.0pt 90.0pt;}
div.Section1
{page:Section1;}
-->

    在运行上面的程序后,由于
newTask方法通过
Sleep延迟了
2秒,因此,程序直到
2秒后才输出最终结果(一个随机整数)。如果不调用
EndInvoke方法,程序会立即退出,这是由于使用
BeginInvoke创建的线程都是后台线程,这种线程一但所有的前台线程都退出后(其中主线程就是一个前台线程),不管后台线程是否执行完毕,都会结束线程,并退出程序。关于前台和后台线程的详细内容,将在后面的部分讲解。

    读者可以使用上面的程序做以下实验。首先在
Main方法的开始部分加入如下代码:

Thread.Sleep(10000);

    以使
Main方法延迟
10秒钟再执行下面的代码,然后按
Ctrl+F5运行程序,并打开企业管理器,观察当前程序的线程数,假设线程数是
4,在
10秒后,线程数会增至
5,这是因为调用
BeginInvoke方法时会建立一个线程来异步执行
newTask方法,因此,线程会增加一个。

四、使用
IAsyncResult asyncResult
属性来判断异步调用是否完成

   

虽然上面的方法可以很好地实现异步调用,但是当调用
EndInvoke
方法获得调用结果时,整个程序就象死了一样,这样做用户的感觉并不会太好,因此,我们可以使用
asyncResult
来判断异步调用是否完成,并显示一些提示信息。这样做可以增加用户体验。代码如下:

static
 
void
 Main(
string
[] args)
{
    NewTaskDelegate task 

=
 newTask;
    IAsyncResult asyncResult 

=
 task.BeginInvoke(
2000

null

null
);
 
    

while
 (
!
asyncResult.IsCompleted)
    {
        Console.Write(

"
*
"
);
        Thread.Sleep(

100
);
    }
    

//
 由于异步调用已经完成,因此, EndInvoke会立刻返回结果


    int
 result 
=
 task.EndInvoke(asyncResult);           
    Console.WriteLine(result);
}

<!--
/* Font Definitions */
&#64;font-face
{font-family:宋体;
panose-1:2 1 6 0 3 1 1 1 1 1;}
&#64;font-face
{font-family:""&#64;宋体";
panose-1:2 1 6 0 3 1 1 1 1 1;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
text-align:justify;
text-justify:inter-ideograph;
font-size:10.5pt;
font-family:"Times New Roman";}
/* Page Definitions */
&#64;page
{}
&#64;page Section1
{size:612.0pt 792.0pt;
margin:72.0pt 90.0pt 72.0pt 90.0pt;}
div.Section1
{page:Section1;}
-->
   
上面代码的执行结果如下图所示。

<!--
/* Font Definitions */
&#64;font-face
{font-family:宋体;
panose-1:2 1 6 0 3 1 1 1 1 1;}
&#64;font-face
{font-family:""&#64;宋体";
panose-1:2 1 6 0 3 1 1 1 1 1;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
text-align:justify;
text-justify:inter-ideograph;
font-size:10.5pt;
font-family:"Times New Roman";}
/* Page Definitions */
&#64;page
{}
&#64;page Section1
{size:612.0pt 792.0pt;
margin:72.0pt 90.0pt 72.0pt 90.0pt;}
div.Section1
{page:Section1;}
-->

    由于是异步,所以“
*”可能会在“任务开始”前输出,如上图所示。



五、使用
WaitOne
方法等待异步方法执行完成

   

使用
WaitOne
方法是另外一种判断异步调用是否完成的方法。代码如下:

static
 
void
 Main(
string
[] args)
{
    NewTaskDelegate task 

=
 newTask;
    IAsyncResult asyncResult 

=
 task.BeginInvoke(
2000

null

null
);

    
while
 (
!
asyncResult.AsyncWaitHandle.WaitOne(
100

false
))
    {
         Console.Write(

"
*
"
);              
    }

    
int
 result 
=
 task.EndInvoke(asyncResult);
    Console.WriteLine(result);
}

<!--
/* Font Definitions */
&#64;font-face
{font-family:宋体;
panose-1:2 1 6 0 3 1 1 1 1 1;}
&#64;font-face
{font-family:""&#64;宋体";
panose-1:2 1 6 0 3 1 1 1 1 1;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
text-align:justify;
text-justify:inter-ideograph;
font-size:10.5pt;
font-family:"Times New Roman";}
/* Page Definitions */
&#64;page
{}
&#64;page Section1
{size:612.0pt 792.0pt;
margin:72.0pt 90.0pt 72.0pt 90.0pt;}
div.Section1
{page:Section1;}
-->

   
WaitOne

的第一个参数表示要等待的毫秒数,在指定时间之内,
WaitOne方法将一直等待,直到异步调用完成,并发出通知,
WaitOne方法才返回
true。当等待指定时间之后,异步调用仍未完成,
WaitOne方法返回
false,如果指定时间为
0,表示不等待,如果为
-1,表示永远等待,直到异步调用完成。

六、使用回调方式返回结果



   
上面介绍的几种方法实际上只相当于一种方法。这些方法虽然可以成功返回结果,也可以给用户一些提示,但在这个过程中,整个程序就象死了一样(如果读者在
GUI
程序中使用这些方法就会非常明显),要想在调用的过程中,程序仍然可以正常做其它的工作,就必须使用异步调用的方式。下面我们使用
GUI
程序来编写一个例子,代码如下:

private
 
delegate
 
int
 MyMethod();

private
 
int
 method()
{
    Thread.Sleep(

10000
);
    

return
 
100
;
}

private
 
void
 MethodCompleted(IAsyncResult asyncResult)
{
    

if
 (asyncResult 
==
 
null

return
;
    textBox1.Text 

=
 (asyncResult.AsyncState 
as
 
    MyMethod).EndInvoke(asyncResult).ToString();
}


private
 
void
 button1_Click(
object
 sender, EventArgs e)
{

    MyMethod my 
=
 method;
    IAsyncResult asyncResult 

=
 my.BeginInvoke(MethodCompleted, my);
}

<!--
/* Font Definitions */
&#64;font-face
{font-family:宋体;
panose-1:2 1 6 0 3 1 1 1 1 1;}
&#64;font-face
{font-family:""&#64;宋体";
panose-1:2 1 6 0 3 1 1 1 1 1;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
text-align:justify;
text-justify:inter-ideograph;
font-size:10.5pt;
font-family:"Times New Roman";}
/* Page Definitions */
&#64;page
{}
&#64;page Section1
{size:612.0pt 792.0pt;
margin:72.0pt 90.0pt 72.0pt 90.0pt;}
div.Section1
{page:Section1;}
-->

    要注意的是,这里使用了
BeginInvoke方法的最后两个参数(如果被调用的方法含有参数的话,这些参数将作为
BeginInvoke的前面一部分参数,如果没有参数,
BeginInvoke就只有两个参数了)。第一个参数是回调方法委托类型,这个委托只有一个参数,就是
IAsyncResult,
MethodCompleted方法所示。当
method方法执行完后,系统会自动调用
MethodCompleted方法。
BeginInvoke的第二个参数需要向
MethodCompleted方法中传递一些值,一般可以传递被调用方法的委托,如上面代码中的
my。这个值可以使用
IAsyncResult.AsyncState属性获得。

    由于上面的代码通过异步的方式访问的
form上的一个
textbox,因此,需要按
ctrl+f5运行程序(不能直接按
F5运行程序,否则无法在其他线程中访问这个
textbox,关于如果在其他线程中访问
GUI组件,并在后面的部分详细介绍)。并在
form上放一些其他的可视控件,然在点击
button1后,其它的控件仍然可以使用,就象什么事都没有发生过一样,在
10秒后,在
textbox1中将输出
100

七、其他组件的
BeginXXX


EndXXX

方法



    在其他的
.net组件中也有类似
BeginInvoke
EndInvoke的方法,如
System.Net.HttpWebRequest类的
BeginGetResponse
EndGetResponse方法,下面是使用这两个方法的一个例子:


private
 
void
 requestCompleted(IAsyncResult asyncResult)
{
    

if
 (asyncResult 
==
 
null

return
;
    System.Net.HttpWebRequest hwr 

=
 asyncResult.AsyncState 
as
 System.Net.HttpWebRequest;
    System.Net.HttpWebResponse response 

=
 
(System.Net.HttpWebResponse)hwr.EndGetResponse(asyncResult);
    System.IO.StreamReader sr 

=
 
new
 
System.IO.StreamReader(response.GetResponseStream());
    textBox1.Text 

=
 sr.ReadToEnd();
}

private
 
delegate
 System.Net.HttpWebResponse RequestDelegate(System.Net.HttpWebRequest request);


private
 
void
 button1_Click(
object
 sender, EventArgs e)
{
    System.Net.HttpWebRequest request 

=
 
    (System.Net.HttpWebRequest)System.Net.WebRequest.Create(

"
http://www.cnblogs.com
"
);
    IAsyncResult asyncResult 

=
request.BeginGetResponse(requestCompleted, request);     
}

抱歉!评论已关闭.