Andre Borges
Andre Borges

Reputation: 1442

Replacement for infinite loop

In my console application I have a couple of classes (let's call them MyClass1, MyClass2, ...) having a method that should check the existence of certain records in the database (different classes wait for different records) and return only when the needed records exist. I currently have a simple implementation using an infinite loop and Thread.Sleep. This approach does work, but it tends to cause a high CPU load. What is the way to make these methods more CPU-friendly?

public override void WaitForRecord()
{
    MyDatabaseRecord record = null;

    while (record == null)
    {
        Thread.Sleep(500);
        using (var dc = new MyDataContext())
        {
            record = dc.Documents
                .Where( /*condition*/)
                .SingleOrDefault();
        }
    }   
    Logger.Info("Record with ID " + record.Id + " found at " + DateTime.Now)
}

The usage of these methods is pretty straightforward: the calling code creates a bunch of objects, launches each object's WaitForRecord method using Task.Factory.StartNew, periodically checks whether any tasks have finished execution, and prints the results in the console like this:

MyClass1 is still waiting for record...
MyClass2 has found the record...
...

Upvotes: 0

Views: 215

Answers (1)

Wyatt Earp
Wyatt Earp

Reputation: 1823

Assuming that you're connecting to a SQL (2005 or greater) database, you could look into SqlDependency. Here is an article on code project about SqlDependency and EF:

http://www.codeproject.com/Articles/496484/SqlDependency-with-Entity-Framework

Upvotes: 1

Related Questions