我已经在这里阅读过以前的问题,ConcurrentBag但没有找到多线程实现的实际示例.
ConcurrentBag是一个线程安全的包实现,针对同一个线程生成和使用存储在包中的数据的情况进行了优化.
目前这是我的代码中的当前用法(这是简化而非实际代码):
private void MyMethod()
{
List<Product> products = GetAllProducts(); // Get list of products
ConcurrentBag<Product> myBag = new ConcurrentBag<Product>();
//products were simply added here in the ConcurrentBag to simplify the code
//actual code process each product before adding in the bag
Parallel.ForEach(
products,
new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },
product => myBag.Add(product));
ProcessBag(myBag); // method to process each items in the concurrentbag
}
Run Code Online (Sandbox Code Playgroud)
我的问题:
这是正确的用法ConcurrentBag吗?ConcurrentBag在这种情况下可以使用吗?
对我来说,我认为一个简单List<Product>的手动锁会做得更好.这样做的原因是上面的场景已经打破了" 同一个线程将生成和消费存储在包中的数据 "规则.
另外我还发现 …
如何查询具有用户特定文本输入的记录?
例如在我的表适配器功能中:
SELECT Word, Description, Example
FROM WordLists
WHERE (Word LIKE @SearchKey OR Description LIKE @SearchKey OR Example LIKE @SearchKey)
Run Code Online (Sandbox Code Playgroud)
显然,只有具有某些输入的确切文本的记录才会从DB中获取.我需要做的是获取包含用户输入文本的所有记录.
我只是做了一个简单的实验,使用下面的代码显示进程中的线程总数.
Console.WriteLine("Total Number of Threads: {0}", Process.GetCurrentProcess().Threads.Count);
Parallel.ForEach(
names,
new ParallelOptions {MaxDegreeOfParallelism = Environment.ProcessorCount },
name =>
{
Console.WriteLine(name);
});
Console.Read();
Console.WriteLine("Total Number of Threads: {0}", Process.GetCurrentProcess().Threads.Count);
Run Code Online (Sandbox Code Playgroud)
我在parallel.foreach之前得到12个线程,并在parallel.foreach之后获得了17个线程.
问题: