I am downloading some JSON periodically, say every 10 seconds... When the data arrives, an event is fired. The event fired simply adds the JSON to a BlockingCollection<string>
(to be processed).
I'm trying to process the JSON as fast as possible (as soon as it arrives...):
public class Engine
{
private BlockingCollection<string> Queue = new BlockingCollection<string>();
private DataDownloader DataDownloader;
public void Init(string url, int interaval)
{
dataDownloader = new DataDownloader(url, interaval);
dataDownloader .StartCollecting();
dataDownloader .DataReceivedEvent += DataArrived;
//Kick off a new task to process the incomming JSON
Task.Factory.StartNew(Process, TaskCreationOptions.LongRunning);
}
/// <summary>
/// Processes the JSON in parallel
/// </summary>
private void Process()
{
Parallel.ForEach(Queue.GetConsumingEnumerable(), ProcessJson);
}
/// <summary>
/// Deserializes JSON and adds result to database
/// </summary>
/// <param name="json"></param>
private void ProcessJson(string json)
{
using (var db = new MyDataContext())
{
var items= Extensions.DeserializeData(json);
foreach (var item in items)
{
db.Items.Add(item);
db.SaveChanges();
}
}
}
private void DataArrived(object sender, string json)
{
Queue.Add(json);
Console.WriteLine("Queue length: " + Queue.Count);
}
}
When I run the program, it works and data gets added to the Database, but if I watch the console message from Console.WriteLine("Queue length: " + Queue.Count);
, I get something like this:
1
1
1
1
1
1
1
1
2
3
4
5
6
7
...
I've tried modifying my Process
to look like this:
/// <summary>
/// Processes the JSON in parallel
/// </summary>
private void Process()
{
foreach (var json in Queue.GetConsumingEnumerable())
{
ProcessJson(json);
}
}
I then add multiple Task.Factory.StartNew(Process, TaskCreationOptions.LongRunning);
but I get the same problem...
Does anyone have any idea of what is going wrong here?