Home > Blockchain >  Do all other threads wait for a static method that is currently running to complete before executing
Do all other threads wait for a static method that is currently running to complete before executing

Time:10-15

I have a question about making a certain method static. Visual Studio is suggesting to make a my method static, as it doesn't use any instance members.

Consider this very simple, fictional method:

public Task<List<Item>> GetItems(IQueryable<Item> items)
{
    var items = await items.ToListAsync();

    //imagine something else happening here to, like some processing logic
    return items;
}

But now suppose that dozens of methods in my code base use GetItems to materialize the result of their IQueryables. One of those IQueryables could be a really slow query to execute on the database.

If GetItems() is shared across all threads, wouldn't all threads be impacted because a slow query is also using the static version. In essence, is GetItems "locked" while it is executing the query, barring other threads from using the same method until the slow query has completed? Are all other threads wanting to execute an IQueryable via GetItems delayed because of one small query?

It's something I've been thinking a lot about but cannot find a definite answer to. Does anyone know?

CodePudding user response:

The VS analyzer suggests making the method static because it does not depend on any class members. Making it static has absolutely zero effect on threading. Making other threads calling the same method concurrently block, would require the introduction of some kind of a lock, which obviously would be pointless and a bad idea.

CodePudding user response:

Are all other threads wanting to execute an IQueryable via GetItems delayed because of one small query?

No. Code is separate from data.

A static method can be called concurrently, just like an instance method. The latter just has an extra this on its stack allowing you to reference instance members.

Each call to GetItems() has its own stack and can run the same code concurrently just fine.

  • Related