我有一个来自不同线程的函数。它创建了一个对象列表,现在我需要将它返回到主线程。我该怎么做呢?或者我可以在主线程中创建对象列表并在单独的线程中对其进行操作吗?
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
}
答案 0 :(得分:4)
您可以在C#4.0中使用BlockingCollection。它是线程安全的。
在一个帖子中:
myBlockingCollection.Add(workItem);
在另一个主题中:
while (true)
{
Work workItem = myBlockingCollection.Take();
ProcessLine(workItem);
}
答案 1 :(得分:0)
您可以跨线程共享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
}
}
}