T.Todua
T.Todua

Reputation: 56557

<Class X> does not contain a definition for GetAwaiter - how to rewrite this method

I have been given this code:

    public async Task myServerResponse()
    {
        Task.Run(new Func<Task>(..));
        await this.ConnectSomewhere(...); 
        ...
        // this method does not have any return
    }


    private async Task Connect()
    {
        try
        {
            bool myFlag = true;
            var taskAwaiter = this.myServerResponse().GetAwaiter();
            if (!taskAwaiter.IsCompleted)
            {
                await taskAwaiter;
                taskAwaiter = default(TaskAwaiter);
                myFlag = false;
            }
            if (myFlag)
                taskAwaiter.GetResult();
            
            ...

However, on line where it says await taskAwaiter; it shows

Error CS1061 : 'TaskAwaiter' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'TaskAwaiter' could be found (are you missing a using directive or an assembly reference?)

How can be this method be rewritten correctly? I think something is overcomplicated approach there.

Upvotes: 1

Views: 876

Answers (1)

Fabjan
Fabjan

Reputation: 13676

Well, it seems that you could just use async await and remove the rest of the stuff:

 private async Task Connect()
    {
        try
        {
            await this.myServerResponse();
            ...

Upvotes: 4

Related Questions