Hidalgo
Hidalgo

Reputation: 941

Task async and await

I want the method PrintOrderAsync to execute an external EXE to print an order. The code for method PrintOrderAsync does not show any syntax errors

public async Task<string> PrintOrderAsync(string PrintExe, string ExePath, int nOrderNo)
{
    await Task.Factory.StartNew(() => Process.Start(ExePath + PrintExe, nOrderNo.ToString()));

        return "";
 }

But I am struggling with the syntax for the calling method. Here is what I tried:

Task<string> result = PrintOrderAsync(PrintExe, ExePath, nOrderNo);

And I see syntax error on the above line. What am I missing?

Upvotes: 0

Views: 92

Answers (2)

David Pine
David Pine

Reputation: 24525

Based on the code that you have shared here you are starting a process. This is concerning as you are not actually waiting for the result of the process, in fact -- it is fire and forget regardless of the async and await keywords unless you wait for the process to exit. There are several ways to do this:

public static Task WaitForExitAsync(this Process process, 
    int milliseconds,
    CancellationToken cancellationToken = default(CancellationToken))
{    
    return Task.Run(() => process.WaitForExit(milliseconds), cancellationToken);
}

For example, here is an extension method you could use to wrap the waiting for the process in a Task. It could then be awaited like this:

public async Task PrintOrderAsync(string PrintExe, string ExePath, int nOrderNo)
{
    return Process.Start(ExePath + PrintExe, nOrderNo.ToString())
                  .WaitForExitAsync(5000);
}

// Then you could await it wherever...
await PrintOrderAsync(PrintExe, ExePath, nOrderNo);

Alternatively, if you do not want to wait for it to complete (i.e.; you want fire and forget, like you have now) do this:

Process.Start(ExePath + PrintExe, nOrderNo.ToString())

Do not wrap it in a Task or anything, it is an entirely separate process anyways (personally, I prefer the first option I shared).

Upvotes: 2

M. Tovbin
M. Tovbin

Reputation: 547

Try

string result = await PrintOrderAsync(PrintExe, ExePath, nOrderNo);

Upvotes: 1

Related Questions