封裝WebService的APM爲Async、Await模式利於Asp.Net頁面調用

Wcf針對Async、Await指令直接能夠返回Task<T>結果,可是老舊的系統中仍是會有不少是在用Soap的Webservice。直接在Asp.Net頁面調用APM方法確實比較麻煩,其實能夠直接用TaskFactory封裝APM模式爲.Net4.5的async await模式,便於頁面調用。web

下面上實現代碼,很少廢話,注意註釋:異步

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Services.Protocols;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class _Default : Page
    {
        protected async void Page_Load(object sender, EventArgs e)
        {
            //這裏不直接用AsyncWebService而用父類SoapHttpClientProtocol的緣由是:之後能夠針對不一樣的webservice複用
            SoapHttpClientProtocol soapHttpClient = new global::AsyncWebService("http://localhost:3115/AsyncWebService.asmx");

            //反射建立APM方法異步委託
            var beginFunc = soapHttpClient.GetType()
                .GetMethod("BeginHelloWorld")
                .CreateDelegate(typeof(Func<string, System.AsyncCallback, object, IAsyncResult>), soapHttpClient) as Func<string, System.AsyncCallback, object, IAsyncResult>;
            var endFunc = soapHttpClient.GetType()
                .GetMethod("EndHelloWorld")
                .CreateDelegate(typeof(Func<IAsyncResult, string>), soapHttpClient) as Func<IAsyncResult, string>;

            //打印一下調用異步前線程ID
            StringBuilder sb = new StringBuilder();
            sb.Append("<br />");
            sb.Append("Befort Thread Id:" + Thread.CurrentThread.ManagedThreadId);
            sb.Append("<br />");


            //用TaskFactory封裝APM模式爲.Net4.5的async await模式
            string result = await Task<string>.Factory.FromAsync<string>(beginFunc,
                endFunc, "zhang san", null);


            //打印一下調用異步後線程ID
            sb.Append("After Thread Id:" + Thread.CurrentThread.ManagedThreadId);
            sb.Append("<br />");

            sb.Append(result);

            ltlResult.Text = sb.ToString();
        }
    }
}

注意須要在Aspx前臺啓用Async="true"特性。async

看一下最終的效果:ui

image

前臺隨便敲了點樣式:spa

<div style="padding: 0;background-color: black;color: white;height:100%;width: 100%;margin: 0 auto;font-size:xx-large;">
    <h6>Test Async</h6>
    <p style="color: yellow;">
    <asp:Literal ID="ltlResult" runat="server"></asp:Literal>
        </p>
</div>線程

 

本文代碼:http://files.cnblogs.com/files/12taotie21/WebApplication1.rarserver

相關文章
相關標籤/搜索