frenchie
frenchie

Reputation: 52017

multithreading: starting a thread to execute a query while another process keeps going

I have a method that looks like this:

public void SomeMethod()
{
    foreach (SomeModel x in TheListOfSomeModel)
    {
        do some work
        ....
        if (SomeCondition)
        {
             x.ExecuteQuery();
        }
    }
}

Basically, SomeModel has a method that runs an update query that stores a property of the object into a field in the database. As the code is currently written, if the query needs to run, the whole loop is on hold until the query is done. If if can be of any use, there are only 5 elements in TheListOfSomeModel.

Apart from using Parrallel ForEach, how can I change this so that the x.ExecuteQuery() runs on a separate thread?

Thanks.

Upvotes: 1

Views: 869

Answers (3)

Damon Friendship
Damon Friendship

Reputation: 781

You can run it as a task like this...

Task.Factory.StartNew(() => x.ExecuteQuery());

Upvotes: 3

sparky68967
sparky68967

Reputation: 647

Exception handling left out for brevity:

using System.Threading.Tasks;    
....

public void SomeMethod()
{
    Task.Factory.StartNew(()=>
    {
        foreach (SomeModel x in TheListOfSomeModel)
        {
            //do some work
            ....
            if (SomeCondition)
            {
                 x.ExecuteQuery();
            }
         }
     });
}

That will run it in a new thread. If are doing this with a UI and you get CrossThreadExceptions then you'll need to access UI controls via Invoke or BeginInvoke.

Upvotes: 0

BrokenGlass
BrokenGlass

Reputation: 160982

Be careful not to close over the loop variable when spawning a task / thread (unless you work with C# 5), also make sure you use a separate connection/context for each thread.

public void SomeMethod()
{
    foreach (SomeModel x in TheListOfSomeModel)
    {
        var model = x;
        //do some work
        ....
        if (SomeCondition)
        {
             Task.Factory.StartNew(() => model.ExecuteQuery());
        }
    }
}

Upvotes: 2

Related Questions