cannot await object in the async call

I have a method called DoSomething() that returns an object and is time-consuming. So I would like to use async/await to let it run in the background while my GUI is showing a "waiting for response..." message.

In my calling method:

Task taskDoSomething = new Task(DoSomethingAsync);
taskDoSomething.Start();
taskDoSomething.Wait();
// continue the program

My DoSomethingAsync method:

private async void DoSomethingAsync()
{
    Object result = await DoSomething();
}

But I am getting the error:

Cannot await [ObjectType]

And [ObjectType] is a type of object I have created myself. I just used object above not to confuse the reader.

Please let me know what I am doing wrong and set me free of the scattered processing of BackgroundWorker.

Jon Skeet
people
quotationmark

I think you've misunderstood how async and await works. If DoSomething() is a long-running method which isn't designed for asynchrony, you probably just want to do it in a different thread, e.g. by starting a separate task:

Task<object> task = Task.Run<object>(DoSomething);

Note that means DoSomething won't be able to interact with the UI, as it'll be on a different thread.

You can then await that task, if you want to - but only from an async method. It's hard to give more concrete advice without knowing more context.

From your comments, you might have something like:

private async void HandleButtonClick(object sender, EventArgs e)
{
    Task<object> task = Task.Run<object>(DoSomething);
    object result = await task;
    status.Text = "I've done something";
    // Use the result?
}

people

See more on this question at Stackoverflow