.NET4.0版本中基于任务的异步模式(TAP)

2022-07-15,,,

一、引言

当使用apm的时候,首先我们要先定义用来包装回调方法的委托,这样难免有点繁琐, 然而使用eap的时候,我们又需要实现completed事件和progress事件,上面两种实现方式感觉都有点繁琐。

同时微软也意识到了这点,所以在.net 4.0中提出了一个新的异步模式——基于任务的异步模式tap(task-based asynchronous pattern )。

基于任务的异步模式 (tap) 是基于 system.threading.tasks.task 命名空间中的 system.threading.tasks.task 和 system.threading.tasks类型,这些类型用于表示任意异步操作。是用于新开发的建议的异步设计模式。

二、什么是tap——基于任务的异步模式介绍

当看到类中存在taskasync为后缀的方法时就代表该类实现了tap并且基于任务的异步模式同样也支持异步操作的取消和进度的报告的功能。

在tap实现中,我们只需要通过向异步方法传入cancellationtoken 参数,因为在异步方法内部会对这个参数的iscancellationrequested属性进行监控,当异步方法收到一个取消请求时,异步方法将会退出执行。

在tap中,我们可以通过iprogress接口来实现进度报告的功能。

1、计算密集型任务

例如,请考虑使用呈现图像的异步方法。

任务的主体可以轮询取消标记,如果在呈现过程中收到取消请求,代码可提前退出。 此外,如果启动之前收到取消请求,你需要阻止操作:

internal task renderasync(imagedata data, cancellationtoken cancellationtoken)
{
    return task.run(() =>
    {
        var bmp = new bitmap(data.width, data.height);
        for(int y=0; y)
        {
            cancellationtoken.throwifcancellationrequested();
            for(int x=0; x)
            {
                // render pixel [x,y] into bmp
            }
        }
        return bmp;
    }, cancellationtoken);
}

2、i/o 密集型任务:

假设你想创建一个将在指定时间段后完成的任务。 例如,你可能想延迟用户界面中的活动。

system.threading.timer 类已提供在指定时间段后以异步方式调用委托的能力,并且你可以通过使用 taskcompletionsource 将 task 前端放在计时器上,例如:

public static task delay(int millisecondstimeout)
   {
       taskcompletionsource tcs = null;
       timer timer = null;

       timer = new timer(delegate
       {
           timer.dispose();
           tcs.trysetresult(datetimeoffset.utcnow);
       }, null, timeout.infinite, timeout.infinite);

       tcs = new taskcompletionsource(timer);
       timer.change(millisecondstimeout, timeout.infinite);
       return tcs.task;
   }

从 .net framework 4.5 开始,task.delay 方法正是为此而提供的,并且你可以在另一个异步方法内使用它。例如,若要实现异步轮询循环:

public static async task poll(uri url, cancellationtoken cancellationtoken,  iprogress<bool> progress)
{
    while(true)
    {
        await task.delay(timespan.fromseconds(10), cancellationtoken);
        bool success = false;
        try
        {
            await downloadstringasync(url);
            success = true;
        }
        catch { /* ignore errors */ }
        progress.report(success);
    }
}

三、如何使用tap——使用基于任务的异步模式来异步编程

下面就让我们实现自己的异步方法(亮点为只需要一个方法就可以完成进度报告和异步操作取消的功能)

// download file cancellationtoken 参数赋值获得一个取消请求 progress参数负责进度报告
private void downloadfile(string url, cancellationtoken ct, iprogress<int> progress)
{
    httpwebrequest request = null;
    httpwebresponse response = null;
    stream responsestream = null;
    int buffersize = 2048;
    byte[] bufferbytes = new byte[buffersize];
    try
    {
        request = (httpwebrequest)webrequest.create(url);
        if (downloadsize != 0)
        {
            request.addrange(downloadsize);
        }

        response = (httpwebresponse)request.getresponse();
        responsestream = response.getresponsestream();
        int readsize = 0;
        while (true)
        {
            // 收到取消请求则退出异步操作
            if (ct.iscancellationrequested == true)
            {
                messagebox.show(string.format("下载暂停,下载的文件地址为:{0}\n 已经下载的字节数为: {1}字节", downloadpath, downloadsize));

                response.close();
                filestream.close();
                sc.post((state) =>
                {
                    this.btnstart.enabled = true;
                    this.btnpause.enabled = false;
                }, null);

                // 退出异步操作
                break;
            }

            readsize = responsestream.read(bufferbytes, 0, bufferbytes.length);
            if (readsize > 0)
            {
                downloadsize += readsize;
                int percentcomplete = (int)((float)downloadsize / (float)totalsize * 100);
                filestream.write(bufferbytes, 0, readsize);

                // 报告进度
                progress.report(percentcomplete);
            }
            else
            {
                messagebox.show(string.format("下载已完成,下载的文件地址为:{0},文件的总字节数为: {1}字节", downloadpath, totalsize));

                sc.post((state) =>
                {
                    this.btnstart.enabled = false;
                    this.btnpause.enabled = false;
                }, null);

                response.close();
                filestream.close();
                break;
            }
        }
    }
    catch (aggregateexception ex)
    {
        // 因为调用cancel方法会抛出operationcanceledexception异常 将任何operationcanceledexception对象都视为以处理
        ex.handle(e => e is operationcanceledexception);
    }
}

这样只需要上面的一个方法,我们就可以完成上一专题中文件下载的程序,我们只需要在下载按钮的事件处理程序调用该方法和在暂停按钮的事件处理程序调用cancellationtokensource.cancel方法即可,具体代码为:

#region 字段

private int downloadsize = 0;
private string downloadpath = null;
private long totalsize = 0;
private filestream filestream;

private cancellationtokensource cts = null;
private task task = null;

private synchronizationcontext sc;

#endregion 字段

#region 构造函数

public filedownloadform()
{
    initializecomponent();
    string url = "http://download.microsoft.com/download/7/0/3/703455ee-a747-4cc8-bd3e-98a615c3aedb/dotnetfx35setup.exe";
    txburl.text = url;
    this.btnpause.enabled = false;

    // get total size of the download file
    gettotalsize();
    downloadpath = environment.getfolderpath(environment.specialfolder.desktop) + "\\" + path.getfilename(this.txburl.text.trim());
    if (file.exists(downloadpath))
    {
        fileinfo fileinfo = new fileinfo(downloadpath);
        downloadsize = (int)fileinfo.length;
        if (downloadsize == totalsize)
        {
            string message = "there is already a file with the same name, do you want to delete it? if not, please change the local path. ";
            var result = messagebox.show(message, "file name conflict: " + downloadpath, messageboxbuttons.okcancel);

            if (result == system.windows.forms.dialogresult.ok)
            {
                file.delete(downloadpath);
            }
            else
            {
                progressbar1.value = (int)((float)downloadsize / (float)totalsize * 100);
                this.btnstart.enabled = false;
                this.btnpause.enabled = false;
            }
        }
    }
}

#endregion 构造函数

#region 方法

// start download file
private void btnstart_click(object sender, eventargs e)
{
    filestream = new filestream(downloadpath, filemode.openorcreate);
    this.btnstart.enabled = false;
    this.btnpause.enabled = true;

    filestream.seek(downloadsize, seekorigin.begin);

    // 捕捉调用线程的同步上下文派生对象
    sc = synchronizationcontext.current;

    cts = new cancellationtokensource();
    // 使用指定的操作初始化新的 task。
    task = new task(() => actionmethod(cts.token), cts.token);

    // 启动 task,并将它安排到当前的 taskscheduler 中执行。
    task.start();

    //await downloadfileasync(txburl.text.trim(), cts.token,new progress(p => progressbar1.value = p));
}

// 任务中执行的方法
private void actionmethod(cancellationtoken ct)
{
    // 使用同步上文文的post方法把更新ui的方法让主线程执行
    downloadfile(txburl.text.trim(), ct, new progress<int>(p =>
        {
            sc.post(new sendorpostcallback((result) => progressbar1.value = (int)result), p);
        }));
}

// pause download
private void btnpause_click(object sender, eventargs e)
{
    // 发出一个取消请求
    cts.cancel();
}

// get total size of file
private void gettotalsize()
{
    httpwebrequest myhttpwebrequest = (httpwebrequest)webrequest.create(txburl.text.trim());
    httpwebresponse response = (httpwebresponse)myhttpwebrequest.getresponse();
    totalsize = response.contentlength;
    response.close();
}

四、与其他异步模式和类型互操作

1、从 apm 到 tap

可以使用 taskfactory.fromasync 方法来实现此操作的 tap 包装,如下所示:

public static task<int> readasync(this stream stream,  byte[] buffer, int offset,  int count)
{
    if (stream == null) 
       throw new argumentnullexception("stream");
    
    return task<int>.factory.fromasync(stream.beginread,  stream.endread, buffer,   offset, count, null);
}

此实现类似于以下内容: 

 public static task<int> readasync(this stream stream,  byte [] buffer, int offset,   int count)
 {
    if (stream == null) 
        throw new argumentnullexception("stream");

    var tcs = new taskcompletionsource<int>();

    stream.beginread(buffer, offset, count, iar =>
                     {
                        try { 
                           tcs.trysetresult(stream.endread(iar)); 
                        }
                        catch(operationcanceledexception) { 
                           tcs.trysetcanceled(); 
                        }
                        catch(exception exc) { 
                           tcs.trysetexception(exc); 
                        }
                     }, null);
    return tcs.task;
}

2、从eap到 tap

public static task<string> downloadstringasync(uri url)
 {
     var tcs = new taskcompletionsource<string>();

     var wc = new webclient();

     wc.downloadstringcompleted += (s,e) =>
         {
             if (e.error != null) 
                tcs.trysetexception(e.error);
             else if (e.cancelled) 
                tcs.trysetcanceled();
             else 
                tcs.trysetresult(e.result);
         };
     wc.downloadstringasync(url);
     return tcs.task;
}

到此这篇关于.net4.0异步模式(tap)的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持。

《.NET4.0版本中基于任务的异步模式(TAP).doc》

下载本文的Word格式文档,以方便收藏与打印。