是否在两个线程之间交换数据
本文关键字:线程 之间 交换 数据 两个 是否 | 更新日期: 2023-09-27 18:04:08
我有一个函数从不同的线程调用。它创建了一个对象列表现在我需要把它返回到主线程。我该怎么做呢?或者我可以在主线程中创建对象列表并在单独的线程中操作它?
Main thread
Thread t = new Thread(Quote);
t.Start(workList);
private void Quote(object obj)
{
List<Work> works = new List<Work>();
works = (List<Work>)obj;
foreach (Work w in works)
{
//do something w
}
//return works to main thread
}
你可以在c# 4.0中使用BlockingCollection。是线程安全的。
在一个线程中: myBlockingCollection.Add(workItem);
在另一个线程:
while (true)
{
Work workItem = myBlockingCollection.Take();
ProcessLine(workItem);
}
你可以跨线程共享List资源,但你要对同步负责,List对象不是线程安全的。使用以下代码片段
Thread t = new Thread(Quote);
t.Start();
private List<Work> workList = new List<Work>(); // Shared across the threads, they should belong to the same class, otherwise you've to make it public member
private void Quote()
{
lock(workList) // Get a lock on this resource so other threads can't access it until my operation is finished
{
foreach (Work w in works)
{
// do something on the workList items
}
}
}