K232
K232

Reputation: 1069

Async in VS 2010 does not work

I'm using Visual Studio 2010 and therefore installed the Visual Studio Async CTP (Version 3) in order to use async and await. I've checked the included samples 'AsnycSamplesVB'. These samples all work fine. But when I copy e.g. 'AsyncResponsiveCPURun' into a new console application, it compiles but only displays the initial line ('Processing data...') and then stops. It calls ProcessDataAsync once but no output...? Any ideas what I'm doing wrong? Here is the complete code in my console application. It's all copied from Microsofts Sample, except the call in Sub Main:

Module Module1

Sub Main()
    AsyncResponsiveCPURun()
End Sub

Public Async Function AsyncResponsiveCPURun() As Threading.Tasks.Task
    Console.WriteLine("Processing data...  Drag the window around or scroll the tree!")
    Console.WriteLine()
    Dim data As Integer() = Await ProcessDataAsync(GetData(), 16, 16)
    Console.WriteLine()
    Console.WriteLine("Processing complete.")
End Function


Public Function ProcessDataAsync(ByVal data As Byte(), ByVal width As Integer, ByVal height As Integer) As Threading.Tasks.Task(Of Integer())
    Return Threading.Tasks.TaskEx.Run(
        Function()
            Dim result(width * height) As Integer
            For y As Integer = 0 To height - 1
                For x As Integer = 0 To width - 1
                    Threading.Thread.Sleep(10)   ' simulate processing cell [x,y]
                Next
                Console.WriteLine("Processed row {0}", y)
            Next
            Return result
        End Function)
End Function
Public Function GetData() As Byte()
    Dim bytes(0 To 255) As Byte
    Return bytes
End Function
End Module

Upvotes: 0

Views: 2181

Answers (1)

K232
K232

Reputation: 1069

Found the answer at Async / Await FAQ on MSDN:

Sub Main()
    AsyncResponsiveCPURun().Wait()
End Sub

Can I use “await” in console apps?

Sure. You can’t use “await” inside of your Main method, however, as entry points can’t be marked as async. Instead, you can use “await” in other methods in your console app, and then if you call those methods from Main, you can synchronously wait (rather than asynchronously wait) for them to complete, e.g.

public static void Main()
{ 
    FooAsync().Wait();
}

private static async Task FooAsync()
{ 
    await Task.Delay(1000); 
    Console.WriteLine(“Done with first delay”); 
    await Task.Delay(1000);
}

Upvotes: 2

Related Questions