我想在自托管 OWIN 环境中的 ApiController 中运行长时间运行的任务(例如 4-5 分钟)。但是,我想在开始该任务后(一旦开始长时间运行的任务)就发回响应,而不等待它完成。这个长时间运行的任务与 HTTP 无关,并且顺序运行一些可能需要很长时间的方法。
我看一下this http://www.hanselman.com/blog/HowToRunBackgroundTasksInASPNET.aspx博客文章并决定尝试一下QueueBackgroundWorkItem
。但是,我不确定是否可以在自托管(控制台应用程序)owin环境中使用此方法或是否有必要使用它。在自托管控制台应用程序中,我认为应用程序本身管理请求,并且所有请求在同一个 AppDomain 中运行(应用程序默认 AppDomain,我们不创建任何新的 appDomain),所以我可能可以在一种一劳永逸的时尚,而不做任何特别的事情?
无论如何,当我使用QueueBackgroundWorkItem
,我总是收到错误:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Operation is not valid due to the current state of the object.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
at System.Web.Hosting.HostingEnvironment.QueueBackgroundWorkItem(Func`2 workItem) at BenchMarkService.SmokeTestController.IsItWorking() in C:\Devel\Code\Projects\BenchMarkService\BenchMarkService\SmokeTestController.cs:line 18 at lambda_method(Closure , Object , Object[] ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
</StackTrace>
</Error>
我还发现this https://stackoverflow.com/questions/17577016/long-running-task-in-webapi关于SO的问题,说实话,这对我来说似乎有点令人困惑,因为实现这一目标的唯一方法是IRegisteredObject
or not?
我只是想在自托管应用程序中运行一个长时间运行的任务,我很欣赏对此的任何想法。我发现的几乎所有资源、问题都是基于asp .net,我不知道从哪里开始。