我已经实现了一个http模块,该模块将在我的ASP.NET应用程序的应用程序启动时触发
using System.Web;
using System.Threading.Tasks;
using System;
using System.Net.Http;
namespace BL.HttpModules
{
public class MyCustomAsyncModule : IHttpModule
{
#region Static Privates
private static bool applicationStarted = false;
private readonly static object applicationStartLock = new object();
#endregion
public void Dispose()
{
}
/// <summary>
/// Initializes the specified module.
/// </summary>
/// <param name="httpApplication">The application context that instantiated and will be running this module.</param>
public void Init(HttpApplication httpApplication)
{
if (!applicationStarted)
{
lock (applicationStartLock)
{
if (!applicationStarted)
{
// this will run only once per application start
this.OnStart(httpApplication);
}
}
}
// this will run on every HttpApplication initialization in the application pool
this.OnInit(httpApplication);
}
public virtual void OnStart(HttpApplication httpApplication)
{
httpApplication.AddOnBeginRequestAsync(OnBegin, OnEnd);
}
private IAsyncResult OnBegin(object sender, EventArgs e, AsyncCallback cb, object extraData)
{
applicationStarted = true;
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;
}
async Task DoAsyncWork(HttpContext ctx)
{
var client = new HttpClient();
var result = await client.GetStringAsync("http://google.com");
// USE RESULT
}
private void OnEnd(IAsyncResult ar)
{
Task t = (Task)ar;
t.Wait();
}
/// <summary>Initializes any data/resources on HTTP module start.</summary>
/// <param name="httpApplication">The application context that instantiated and will be running this module.</param>
public virtual void OnInit(HttpApplication httpApplication)
{
// put your module initialization code here
}
}// end class
}// end namespace
我想在每5分钟后解雇DoAsyncWork。你能帮助我在那个模块中实现这个目标吗?
答案 0 :(得分:0)
IIS中没有内置的方法来可靠地执行此操作,您需要使用外部进程或第三方库来安排要完成的工作。 Hangfire是一个非常受欢迎的库,可让您同时处理进程和进程外的计划任务。