SharpNoiZy
SharpNoiZy

Reputation: 1119

EF Linq Select and Update or vise versa in one step

I have the situation that I have multiple async windows services. All are working with one table "Jobs". Let's say with two columns: "Id" and "Loaded"

In this table are 50 jobs.
What I want now is that this services grap every time only 10 jobs and work on them.

But it is really important that a job will not be processed twice. The services grap only jobs where "Loaded" is null.

And if now "Service A" comes and load the first 10 jobs where "Loaded" is null what maybe take 5 sec. And within this 5 sec. "Service B" comes and also load 10 jobs, this jobs will be the same. (DANGER!)

What I want to do now, to avoid double processed jobs, is to load the 10 jobs and update them ("Loaded" to DateTime.UtcNow) in one statement or update the them and load the affected in one statement.

But I don't know if this is possible. Can someone help me?

Kind regards

Upvotes: 0

Views: 164

Answers (2)

faby
faby

Reputation: 7558

I think that you can do something like this

   list.Where(j => j.Loaded == null).Take(10).AsEnumerable()
                .Select(x =>
                {
                    x.Loaded = DateTime.UtcNow;
                    db.SaveChanges();
                    return x;
                })
                .ToList().ForEach(j => //proccess job here);

Upvotes: 1

Alex Barac
Alex Barac

Reputation: 633

You have a problem of concurrent database access. Your purpose is to update each job that was read with a flag so that it is not processed a second time. Two ideas come to mind :

  • Exclusive database access You will only allow one windows service to read and update the records it read at one time. This will assure that no job is processed twice.
  • Read all the items Read all the available jobs every time, then distribute them to each windows service. You'll have to implement some form of data sharing between the application that reads the jobs and the windows services. This idea allows you to have more control over what job each service processes.

Upvotes: 0

Related Questions