Search code examples
c#async-ctpasync-await

Error with async await keywords


i added the AsyncCtpLibrary v.3. grabbed some sample code from the async webpage. wrapped it in a TestFixture to play around with.

i'm getting errors: any ideas why?

Error 1 - Invalid token 'void' in class, struct, or interface member declaration

Error 2 - ; expected

code:

 [TestFixture]
public class AsyncTests
{
    [Test]
    public async void AsyncRunCpu()
    {
        Console.WriteLine("On the UI thread.");

        int result = await TaskEx.Run(
            () =>
                {
                    Console.WriteLine("Starting CPU-intensive work on background thread...");
                    int work = DoCpuIntensiveWork();
                    Console.WriteLine("Done with CPU-intensive work!");
                    return work;
                });

        Console.WriteLine("Back on the UI thread.  Result is {0}.", result);
    }

    public int DoCpuIntensiveWork()
    {
        // Simulate some CPU-bound work on the background thread:
        Thread.Sleep(5000);
        return 123;
    }
}

Solution

  • I think it's supposed to be:

    [Test]
    public async Task AsyncRunCpu()
    {
        // ...
    }
    

    as far as I can tell async methods with a void return type are in some way special - wonder why the compiler doesn't issue a warning for this kind of scenario ...

    By the way you can use async/await with .NET4.0, just add a reference to Microsoft.BCL.Async in the project. The only difference is that some Task related functionality lives in the TaskEx type.