开发者

Task.Factory.StartNew "action" argument and higher level local variables

Consider this:

void StartUpdate(DataRequest dataRequest)
{
    Task.Factory.StartNew(request => {... do something with "request" ...}, 
        dataRequest);
}

Now, my question: can I use dataRequest inside the lambda expression, instead of passing it as second parameter to StartNew method? My concern is - that method will be executed on a dif开发者_StackOverflowferent thread and I'm not sure if dataRequest would keep its state when used there.


Yes, you can.
This is called a Closure; it's a very powerful feature.

The thread-safety, or lack thereof, will be no different.
Whether you get the instance through the closure or through a StartNew parameter, it's still the same object. (Unless it's a struct, which would be indescribably evil)


I had the same problem. Use Action instead of the lambda expression.

private void StartUpdate(DataRequest dataRequest)
{
    Action<DataRequest> pobjAction = new Action<DataRequest>(DoSomething);
    Task.Factory.StartNew(pobjAccion, dataRequest);
}


private void DoSomething(DataRequest dataRequest)
{
    Trace.WriteLine(dataRequest.ToString());
}


Answer to your question, You can but it may not threadsafe. I learn to use ThreadLocal to help.

inside your delegate method should Isolate your dataRequest.

ThreadLocal<DataRequest> tls = new ThreadLocal<DataRequest>();

Task.Factory.StartNew(request => {
   tls.Value = (DataRequest)stateObject;

   ///
}, dataRequest);

/* I get it from Pro .NET Parallel Programming in C# */

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜