Since you tagged the question with azure-webjobs-sdk
and I remember that you had another question a few days ago about the SDK, I will assume your webjob uses the SDK and the multithreading is caused by the fact that we running triggered functions in parallel.
The first part of my answer is not necessarily web jobs related:
class Program
{
private static MyService _service;
private static int _counter;
private static readonly object _lock = new object();
// The 3 blocks of code are thread safe by themselves
// but put together, there is no guarantee. Avoid
// multiple locks if you can
private static void Method1()
{
// 1. You can use a lock
lock(_lock)
{
// All the code here will be executed by a single thread.
// If another thread tries to get the lock, it will have
// to wait until the lock is released
_service.DoSomething();
}
// 2. For atomic operations you can use Interlocked
Interlocked.Increment(ref _counter);
// 3. For conditional locking
if (_service.SomeBooleanProperty)
{
lock(_lock)
{
// Check again to see the condition still holds
// because it might have changed between the
// execution of the first if and the lock
if (_service.SomeBooleanProperty)
{
// Execute the non thread safe code
}
}
}
}
}
Reference to the Interlocked class
Now I'm talking WebJobs SDK:
If you want to control the concurrency for processing, you can set the Queue.BatchSize
property. By default is 16. If you set it to 1, everything runs sequential. See the reference here. If you are having concurrency issues with multi instance concurrency (multiple instances of the same job) then blob leases are the way to go.