我浏览了堆栈溢出等文章和链接但是如何在.Net 4.0中实现fire and forget概念?任何人都可以详细解释一下。
通过使用Fire和Forget概念来表现,即;页面加载所花费的时间最小化了吗?enter code here
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 AJGSourceIPModuleNet4
{
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();
var result = await client.GetStringAsync("http://foo.com");
// use result
int result = await FireAndForgetInternal();
}
private Task<int> FireAndForgetInternal()
{
return System.Threading.Tasks.TaskEx.Run(() =>
{
TaskEx.Delay(10000);
return 42; // meaning of life
});
}
}
这是使用FireAndForget的正确方法吗?我不想等待结果。请指导。
由于