Traditional way we do is lock the collection's syncroot property.
For example:
Hashtable ht=new Hashtable();
lock (ht.SyncRoot)
{
...//do somthing
}
Notice that the lock of "this" (lock(this)). or lock of an object instance is not a thread safe method. And Syncronized method is not thread safe for collections as well.
After C# 4.0 comming out, there is a new data structure: Concurrent Collection, and this data type makes thread safe.
We write an sample code below to use Concurrent Collection:
using System;
using System.Net;
using System.Threading.Tasks;
using System.Collections.Concurrent;
class Program
{
static void Main(string[] args)
{
var links = new ConcurrentQueue
links.Enqueue("http://....aa.jpg");
links.Enqueue("http://....bb.jpg");
links.Enqueue("http://....cc.jpg");
Parallel.For(0, links.Count, delegate(int i)
{
string url;
string filename = "Product"+i + "test.jpg";
if (links.TryDequeue(out url))
{
DownLoad(url, filename);
}
});
}
private static void DownLoad(string url,string filename)
{
using (WebClient wc = new WebClient())
{
wc.DownloadFile(url, filename);
}
}
}
For the other Concurrent Data Type, such as ConcurrentBag, ConcurrentStack, ConcurrentList, please check msdn for use.
No comments:
Post a Comment