开发者

Exchanging data between two threads or not?

开发者 https://www.devze.com 2023-03-24 05:53 出处:网络
I have function called from a different thread. And it creats a list of objects and now I need to return it to the main thread. How do I do this? Or can I just create the list of objects i开发者_运维技

I have function called from a different thread. And it creats a list of objects and now I need to return it to the main thread. How do I do this? Or can I just create the list of objects i开发者_运维技巧n the main thread and manipulate it in the separate thread?

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
}


You can use the BlockingCollection in C# 4.0. It is thread-safe.

In one thread:

 myBlockingCollection.Add(workItem);

In another thread:

 while (true)
 {
     Work workItem = myBlockingCollection.Take();
     ProcessLine(workItem);
 }


You can share the List resource across your thread but you'll be responsible about the synchronization, List objects are not thread safe. Use this snippet of code

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
         }
     }
}
0

精彩评论

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