user13113155
user13113155

Reputation:

How make method start new execution only when finished previous execution

Hello How make method MethodA start new execution only when finished previous execution?

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        MethodB();
        MethodC();
    }

    public static void MethodA ()
    {
        Console.WriteLine("Start");
        Thread.Sleep(200);
        Console.WriteLine("Stop");
    }

    public static void MethodB()
    {
        Task.Run(() => MethodA());
    }

    public static void MethodC()
    {
        Task.Run(() => MethodA());
    }
}

In this case I have this result

Hello World
Start
Start
Stop
Stop

But I need something like this

Hello World
Start
Stop
Start
Stop

Upvotes: 0

Views: 50

Answers (2)

D Stanley
D Stanley

Reputation: 152511

The simplest way is to create a static locking object and reference that in MethodA:

private static readonly object _methodALockObject = new object();

public static void MethodA()
{
    lock(_methodALockObject)
    {
        Console.WriteLine("Start");
        Thread.Sleep(200);
        Console.WriteLine("Stop");
    }
}

Upvotes: 1

StepUp
StepUp

Reputation: 38094

Try to use async and await:

public static void Main()
{   
    Task.Run(async () =>
    {
         await MethodB();
         await MethodC();
    }).GetAwaiter().GetResult();
}

public static void MethodA()
{
    Console.WriteLine("Start");
    Thread.Sleep(200);
    Console.WriteLine("Stop");
}

public async static Task MethodB()
{
    await Task.Run(() => MethodA());
}

public async static Task MethodC()
{
    await Task.Run(() => MethodA());
}

async and await keywords help to make your asynchronous code to be executed in syncronous order.

Upvotes: 0

Related Questions