0

下面是我在 .Net 4.0 中用于开发 Http Module 的代码。但是当程序运行时,我发现它要等待几秒钟才能运行应用程序。但我希望它是 FireAndForget() [不应该等待结果]。我怎样才能让它FireAndForget?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Configuration;

namespace SourceIPModuleNet4
{
    public class HttpModule4 : IHttpModule
    {
        public void Dispose()
        {
        }

        public void Init(HttpApplication app)
        {
            app.AddOnBeginRequestAsync(OnBegin, OnEnd);
        }

        private IAsyncResult OnBegin(object sender, EventArgs e, AsyncCallback cb, object extraData)
        {
            var tcs = new TaskCompletionSource<object>(extraData);
            DoAsyncWork(HttpContext.Current).ContinueWith(t =>
            {
                if (t.IsFaulted)
                {
                    tcs.SetException(t.Exception.InnerExceptions);
                }
                else
                {
                    tcs.SetResult(null);
                }
                if (cb != null) cb(tcs.Task);
            });
            return tcs.Task;
        }

        private void OnEnd(IAsyncResult ar)
        {

        }

        private async Task DoAsyncWork(HttpContext ctx)
        {

            var client = new HttpClient();
            Thread.Sleep(10000) // in milliseconds
            var result = await client.GetStringAsync("http://foo.com");

            // use result


        }

    }
4

0 回答 0