gpt4 book ai didi

.net - CallContext.SetData() - 当线程变为事件-非事件-事件 (TPL) 时对象是否可用?

转载 作者:行者123 更新时间:2023-12-01 17:35:38 25 4
gpt4 key购买 nike

各位,

假设我使用线程 10、11、12 中的 CallContext.SetData() 存储对象 Car 的三个新实例。这些线程完成执行。然后我执行另一个多线程操作(可能与第一个操作不同),该操作使用线程 10、11、12。 GetData() 会检索我存储的相同的三个对象吗?或者现在上下文是否有所不同并且这些对象消失了?

我的特定用例是任务并行库。我正在使用 TPL 并行化某些操作,并且我想了解在 TPL 调用之间通过 CallContext.SetData() 存储的数据会发生什么情况。

编辑
根据 @wageoghe 的建议,我尝试了 ThreadLocal,它成功了!

更新了代码来证明这一点:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace TlsTest
{

public class Program
{

public static void Main()
{
Console.WriteLine( "-------using threadpool---------" );
UseThreadPool();
Console.WriteLine( "-------using tasks---------" );
UseTasks();
Console.WriteLine( "-------using parallel for---------" );
UseParallelFor();
Console.ReadKey();
}

public static void UseThreadPool()
{

var finish = new CountdownEvent( TotalThreads );

for ( int i = 0 ; i < TotalThreads ; i++ )
{
ThreadPool.QueueUserWorkItem( x =>
{
int id = Thread.CurrentThread.ManagedThreadId;

Thread.Sleep( SleepMilliseconds );

if ( ThreadId.IsValueCreated )
{
Console.WriteLine( "thread [{0}], tls.thread [{1}] - value already in Tls" , id , ThreadId.Value );
}
else
{
Console.WriteLine( "thread [{0}] - no Tls value" , id );
ThreadId.Value = id;
}
Thread.Sleep( SleepMilliseconds );
finish.Signal();
} );
}
finish.Wait();
}

public static void UseTasks()
{
const TaskCreationOptions taskCreationOpt = TaskCreationOptions.None;

var allTasks = new Task[ TotalThreads ];
for ( int i = 0 ; i < TotalThreads ; i++ )
{
Task task = Task.Factory.StartNew( () =>
{
int id = Thread.CurrentThread.ManagedThreadId;

Thread.Sleep( SleepMilliseconds );

if ( ThreadId.IsValueCreated )
{
Console.WriteLine( "thread [{0}], tls.thread [{1}] - value already in Tls" , id , ThreadId.Value );
}
else
{
Console.WriteLine( "thread [{0}] - no Tls value" , id );
ThreadId.Value = id;
}

Thread.Sleep( SleepMilliseconds );

} , taskCreationOpt );
allTasks[ i ] = task;
}
Task.WaitAll( allTasks );
}

public static void UseParallelFor()
{

var options = new ParallelOptions();
options.MaxDegreeOfParallelism = 8;
Parallel.For( 0 , TotalThreads , options , i =>
{
int id = Thread.CurrentThread.ManagedThreadId;

Thread.Sleep( SleepMilliseconds );

if ( ThreadId.IsValueCreated )
{
Console.WriteLine( "thread [{0}], tls.thread [{1}] - value already in Tls" , id , ThreadId.Value );
}
else
{
Console.WriteLine( "thread [{0}] - no Tls value" , id );
ThreadId.Value = id;
}

Thread.Sleep( SleepMilliseconds );

} );
}

private static readonly ThreadLocal<int> ThreadId = new ThreadLocal<int>();
private const int TotalThreads = 100;
private const int SleepMilliseconds = 500;

}
}

最佳答案

[更新]

实际上,我原来的答案(在这篇文章的底部)似乎有部分错误!

我编写了一个小测试程序,用于测试在 CallContext 中存储来自线程、任务、ThreadPool 线程以及 Parallel.For 中线程的数据的场景。在任务测试和线程池测试中,当重用同一线程(由 ManagedThreadId 确定)时,不会再次看到存储在 CallContext 中的数据。但是,在 Parallel.For 的情况下,当重用同一线程(由 ManagedThreadId 确定)时,会再次看到存储在 CallContext 中的数据。我发现这很有趣。我不确定这些结果是否符合预期,或者我的程序是否有问题。

要尝试每种情况,只需取消注释所需的测试函数即可。

您将看到任务和线程池线程在线程的后续重用中永远不会遇到 CallContext 数据,而 Parallel.For 线程确实会遇到 CallContext 数据。

Parallel.For 的行为似乎不一致。当我运行 Parallel.For 情况时,我可以看到给定线程在重用该线程时不一定总是找到 CallContext 数据。例如,以下是程序一次运行的输出(未注释 UseParallelFor):

thread [9] - no CallContext value
thread [10] - no CallContext value
thread [11] - no CallContext value
thread [12] - no CallContext value
thread [9], cc.thread [9] - value already in CallContext <-- this is expected as this is the main thread
thread [10] - no CallContext value
thread [13] - no CallContext value
thread [11] - no CallContext value
thread [12] - no CallContext value
thread [14] - no CallContext value
thread [9], cc.thread [9] - value already in CallContext
thread [10], cc.thread [10] - value already in CallContext
thread [11], cc.thread [11] - value already in CallContext
thread [13] - no CallContext value
thread [15] - no CallContext value
thread [12], cc.thread [12] - value already in CallContext
thread [16] - no CallContext value
thread [14] - no CallContext value
thread [9], cc.thread [9] - value already in CallContext
thread [10] - no CallContext value
thread [17] - no CallContext value
thread [13], cc.thread [13] - value already in CallContext
thread [15] - no CallContext value
thread [11] - no CallContext value
thread [12] - no CallContext value
thread [14], cc.thread [14] - value already in CallContext
thread [18] - no CallContext value
thread [16] - no CallContext value
thread [9], cc.thread [9] - value already in CallContext
thread [10], cc.thread [10] - value already in CallContext
thread [13] - no CallContext value
thread [15], cc.thread [15] - value already in CallContext
thread [11], cc.thread [11] - value already in CallContext
thread [17] - no CallContext value
thread [19] - no CallContext value
thread [18] - no CallContext value
thread [16], cc.thread [16] - value already in CallContext
thread [14] - no CallContext value
thread [20] - no CallContext value
thread [12], cc.thread [12] - value already in CallContext
thread [9], cc.thread [9] - value already in CallContext
thread [10], cc.thread [10] - value already in CallContext
thread [21] - no CallContext value
thread [15] - no CallContext value
thread [11], cc.thread [11] - value already in CallContext
thread [17], cc.thread [17] - value already in CallContext
thread [13], cc.thread [13] - value already in CallContext
thread [19] - no CallContext value
thread [22] - no CallContext value
thread [18], cc.thread [18] - value already in CallContext
thread [16] - no CallContext value
thread [20] - no CallContext value
thread [14], cc.thread [14] - value already in CallContext
thread [12], cc.thread [12] - value already in CallContext
thread [9], cc.thread [9] - value already in CallContext
thread [10], cc.thread [10] - value already in CallContext
thread [23] - no CallContext value
thread [15], cc.thread [15] - value already in CallContext
thread [21] - no CallContext value
thread [11], cc.thread [11] - value already in CallContext
thread [17] - no CallContext value
thread [13], cc.thread [13] - value already in CallContext
thread [19], cc.thread [19] - value already in CallContext
thread [22] - no CallContext value
thread [16], cc.thread [16] - value already in CallContext
thread [18] - no CallContext value
thread [24] - no CallContext value
thread [20], cc.thread [20] - value already in CallContext
thread [14], cc.thread [14] - value already in CallContext
thread [12], cc.thread [12] - value already in CallContext
thread [9], cc.thread [9] - value already in CallContext
thread [10] - no CallContext value
thread [15], cc.thread [15] - value already in CallContext
thread [21], cc.thread [21] - value already in CallContext
thread [17], cc.thread [17] - value already in CallContext
thread [13], cc.thread [13] - value already in CallContext
thread [22], cc.thread [22] - value already in CallContext
thread [18], cc.thread [18] - value already in CallContext
thread [16], cc.thread [16] - value already in CallContext
thread [14], cc.thread [14] - value already in CallContext
thread [9], cc.thread [9] - value already in CallContext
thread [10], cc.thread [10] - value already in CallContext
thread [15], cc.thread [15] - value already in CallContext
thread [17], cc.thread [17] - value already in CallContext
thread [18], cc.thread [18] - value already in CallContext
thread [16], cc.thread [16] - value already in CallContext
thread [9], cc.thread [9] - value already in CallContext
thread [10], cc.thread [10] - value already in CallContext
thread [17], cc.thread [17] - value already in CallContext
thread [18], cc.thread [18] - value already in CallContext
thread [9], cc.thread [9] - value already in CallContext
thread [10], cc.thread [10] - value already in CallContext
thread [9], cc.thread [9] - value already in CallContext
thread [10], cc.thread [10] - value already in CallContext
thread [9], cc.thread [9] - value already in CallContext
thread [10], cc.thread [10] - value already in CallContext
thread [9], cc.thread [9] - value already in CallContext
thread [10], cc.thread [10] - value already in CallContext
thread [9], cc.thread [9] - value already in CallContext
thread [10], cc.thread [10] - value already in CallContext

正如您所看到的,一旦在重用中找到某个值,它就不会永远保留在 CallContext 中。在某些情况下,对于给定线程的几次迭代,在 CallContext 中找不到该值,因此会添加该值。然后迭代将报告找到该值。然后,也许下一次迭代会说找不到该值。

结果告诉我,您不应该依赖 CallContext 中保持完整的数据,以便在线程重用之间清除给定线程。他们还告诉我,在 Parallel.For 的情况下,您不应该依赖于在同一线程的重用之间清除 CallContext。

这是我的测试程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Threading;
using System.Threading.Tasks;
using System.Runtime.Remoting.Messaging;

namespace CallContextTest
{
class Program
{
static void Main(string[] args)
{
//UseTasks();
//UseThreadPool();
UseParallelFor();

Console.ReadKey();
}

public static void UseThreadPool()
{
int totalThreads = 100;

CountdownEvent finish = new CountdownEvent(totalThreads);

for (int i = 0; i < totalThreads; i++)
{
int ii = i;

ThreadPool.QueueUserWorkItem(x =>
{
int id = Thread.CurrentThread.ManagedThreadId;

Thread.Sleep(1000);

object o = CallContext.GetData("threadid");
if (o == null)
{
//Always gets here.
Console.WriteLine("thread [{0}] - no CallContext value", id);
CallContext.SetData("threadid", id);
}
else
{
//Never gets here.
Console.WriteLine("thread [{0}], cc.thread [{1}] - value already in CallContext", o, id);
}

Thread.Sleep(1000);
finish.Signal();
});

}

finish.Wait();
}

public static void UseTasks()
{
int totalThreads = 100;
TaskCreationOptions taskCreationOpt = TaskCreationOptions.None;
Task task = null;


Task[] allTasks = new Task[totalThreads];
for (int i = 0; i < totalThreads; i++)
{
int ii = i;
task = Task.Factory.StartNew(() =>
{
int id = Thread.CurrentThread.ManagedThreadId;

Thread.Sleep(1000);

object o = CallContext.GetData("threadid");
if (o == null)
{
//Always gets here.
Console.WriteLine("thread [{0}] - no CallContext value", id);
CallContext.SetData("threadid", id);
}
else
{
//Never gets here.
Console.WriteLine("thread [{0}], cc.thread [{1}] - value already in CallContext", o, id);
}

Thread.Sleep(1000);

}, taskCreationOpt);
allTasks[i] = task;
}
Task.WaitAll(allTasks);
}

public static void UseParallelFor()
{
int totalThreads = 100;
Parallel.For(0, totalThreads, i =>
{
int ii = i;
int id = Thread.CurrentThread.ManagedThreadId;

Thread.Sleep(1000);

object o = CallContext.GetData("threadid");
if (o == null)
{
//Sometimes gets here.
Console.WriteLine("thread [{0}] - no CallContext value", id);
CallContext.SetData("threadid", id);
}
else
{
//Sometimes gets here as threads are reused.
Console.WriteLine("thread [{0}], cc.thread [{1}] - value already in CallContext", o, id);
}

Thread.Sleep(1000);

});
}

}
}

注意,根据上面的测试程序和我的新评论,在这个答案的顶部,我原来的讨论似乎是错误的。根据我的测试,对于任务和 ThreadPool 线程,存储在 CallContext 中的数据在后续重用同一线程 ID 时似乎不可用。然而,在 Parallel.For 的情况下,存储在 CallContext 中的数据似乎可以在同一线程的重用中使用。

忽略结束更新后的所有内容。

[结束更新]

我当然不是 TPL 专家,但我最近经常研究 CallContext.SetData(和 LogicalSetData),所以我对 CallContext 的工作原理有一些了解。这里有更好的人来描述 TPL“上下文”中的 CallContext 数据可能会或可能不会发生什么。

我对 CallContext.SetData 工作原理的理解是,当线程消失时,“数据”将被清除。因此,如果您创建一个新线程,并在该线程上执行时,使用 CallContext.SetData 存储一些数据,那么当线程终止时,这些数据将消失。如果您使用的是 ThreadPool 线程,则该线程永远不会死亡(好吧,也许永远太强了),因此通过 CallContext.SetData 存储的数据在下次执行某些代码时仍将存在 (重用)线程。

我的理解是,任务并行库在内部使用 ThreadPool,因此当再次使用底层 ThreadPool 线程时,通过 CallContext.SetData 存储的任何数据可能仍然存在。

编写一个或多个小测试来看看将数据放入 CallContext 时会发生什么,然后检查该数据在同一线程的后续使用中是否存在,应该很容易。

关于.net - CallContext.SetData() - 当线程变为事件-非事件-事件 (TPL) 时对象是否可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4891528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com