简体   繁体   English

将HttpContext传递给Task.Run线程

[英]Passing HttpContext to Task.Run thread

I'm trying to pass HttpContext.Current to the thread created via Task.Run . 我试图将HttpContext.Current传递给通过Task.Run创建的线程。 As I have a Transaction ID in in HttpContext.Items , which I'll need in the thread. 因为我在HttpContext.Items有一个事务ID,所以我需要在线程中。

public static Task<TResult> RunWithContext<TResult>(Func<TResult> function)
{
    var context = HttpContext.Current;                        
    return Task.Run(()=> { RequestHelper.SaveHttpContextInThread(context); return function(); } );
}

public static void SaveHttpContextInThread(HttpContext context)
{
    Thread.SetData(Thread.GetNamedDataSlot(RequestHelper.THREAD_SLOT_NAME), context);
}


var response = TaskHelper.RunWithContext(() => _service.UpdateJob(jobjsonstring));
var jobData = JObject.Parse(response.Result); //Compiler error here

But a compiler error 但是编译错误

'Argument 1: cannot convert from 'System.Threading.Tasks.Task' to 'string' '参数1:无法从'System.Threading.Tasks.Task'转换为'string'

occurs in the last line. 发生在最后一行。

Seems to be an issue with the way I'm returning from the anonymous method. 我从匿名方法返回的方式似乎存在问题。


Update 更新资料

It seems _service.UpdateJob was returning Task but I was expecting it to return Job object, Apologies. 似乎_service.UpdateJob返回Task,但是我希望它返回Job对象,歉意。

Actual Problem: In a WebAPI we want to run some task in a new thread. 实际问题:在WebAPI中,我们希望在新线程中运行某些任务。 There is a value TransactionID in HttpContext.Items. HttpContext.Items中有一个值TransactionID。 We want the newly created thread to be able to read TransactionID. 我们希望新创建的线程能够读取TransactionID。 The above approach was to pass the entire HttpContext to the new thread. 上面的方法是将整个HttpContext传递给新线程。

It can get quite confusing with the nested use of tasks, especially without the use async / await . 嵌套使用任务可能会造成混乱,尤其是在没有使用async / await

The _ service.UpdateJob(jobjsonstring) returns a Task . _ service.UpdateJob(jobjsonstring)返回Task Therefore Task.Run which executes this function returns a Task object with a Task as result. 因此Task.Run其中执行该函数返回一个Task与一个对象Task作为结果。

In order to get the Result of the _ service.UpdateJob call you have to use response.Result.Result . 为了获得_ service.UpdateJob调用的结果,您必须使用response.Result.Result

 var jobData = JObject.Parse(response.Result.Result);

Another alternative (without async/await) is to return the Result inside the function, eg 另一种选择(不使用异步/等待)是在函数内部返回结果,例如

var response = TaskHelper.RunWithContext(() => _service.UpdateJob(jobjsonstring).Result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM