Use only threads for the Web service call and not for the Db call

advertisements

My app in c# is working this way. I start as many threads as it is value in config file (dynamic creation of threads). What every thread is doing is: it goes to DB, calls stored procedure (if I have 60 threads, there are deadlocks). After that, every thread is calling web service, and going back to update rows. Here is how it is looking like

List<Message> messages =getMessages(ThreadNO);//goes to DB

if (messages != null)
{
    foreach (Message bm in messages)
    {
        if (bm.Status)
        {
            try
            {
                bm.send();//calls Web service
            }
            catch (Exception ex)
            {
                LOG.Logger.Error(ex.ToString());
            }
            updateStatus(bm);//goes back to DB
        }
        else
        {
            if (bm.subscribe())
                updateSubscription(bm);//calls WS
            else
                updateUnsuccessfulSubscription(bm);//calls WS
        }
    }
}

I would like to do this in a DB less expensive way. I would like only once to go to DB, and after that to create sublists from object messages. After that I will create as many threads as sublists, and those sublists I will pass to send() method. Each thread will call send() method. But when I finish everything, how can I get out of threads and only once call stored procedure to update (updateMessage() method)? How can I do this in a way to only use threads only to call web service, and at same time to call Db out of threads?


I'm not sure I understand your question completely, but if you want to restrict the database calls to one at a time, you can just use a lock:

// put this field in a class somewhere
static object gate = new object();

// then wrap all your database calls in locks:
lock( gate )
{
  updateStatus(bm);
}

That way, it doesn't matter how many threads try to call the database concurrently, only one call will be able to run at a time.