简体   繁体   中英

C# async method call

I would have a async call to a function as following:

I'll call a method from the main method, this function should be async, how I do this?

A little example:

private static void Main(string[] args)
{
    StartDoingNothingAsync();
    Console.WriteLine("test");
    Console.Read();
}

private static async void StartDoingNothingAsync()
{
    for (var i = 0; i < 5000; i++)
    {
        //do something
    }
    Console.WriteLine("leaved");
}

I would first the output "test", before "leaved", how can I practice this?

The simplest option would be to introduce a delay into your async method:

private static async void StartDoingNothingAsync()
{
    await Task.Delay(1000);
    // This will be called on a thread-pool thread
    Console.WriteLine("leaved");
}

That won't guarantee that test will be printed before leaved , but it seems very likely. If you actually want a guarantee, you'd have to pass something into StartDoingNothingAsync that you then signal after printing test ... but it's not really clear what you're trying to achieve.

Note that async methods should almost never be void - basically that's only available to allow for async event handlers. Make the method return Task instead - that way your calling code can tell when it's completed. (Even if you don't use that fact in this case, it's a good habit to get into.)

Now that we have a bit more information about what you're trying to achieve, I would recommend not making StartDoingNothingAsync an async method - just use a task instead:

private static void Main(string[] args)
{
    Task task = Task.Run(DoSomething);
    Console.WriteLine("test");
    task.Wait();
    Console.Read();
}

static void DoSomething()
{
    // Code to run on a separate thread
}

You can do it like this

private static void Main(string[] args)
    {
        StartDoingNothingAsync();
        Console.WriteLine("test");
        Console.Read();
    }

    private static async void StartDoingNothingAsync()
    {
        await Task.Run(async delegate()
        {
            for (var i = 0; i < 5000; i++)
            {
                //do something
            }
            Console.WriteLine("leaved");
        });
    }

You can use Task for that. In that case you don't need to mark your function as async:

    private static void Main(string[] args)
    {
        new Task(StartDoingNothing).Start();
        Console.WriteLine("test");
        Console.Read();
    }

    private static void StartDoingNothing()
    {
        for (var i = 0; i < 5000; i++)
        {
            //do something
        }
        Console.WriteLine("leaved");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM