如何使应用程序FireandForget?

时间:2015-01-19 02:44:13

标签: .net-4.0 fire-and-forget

以下是我用于在.Net 4.0中开发Http模块的代码。但是当程序运行时,我发现它等待几秒钟才能运行应用程序。但我希望它是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


        }

    }

0 个答案:

没有答案