2

I have a method with a signature like this:

internal async static Task<string> Get()
{
   var SqlCon = await InitializeConnection();
   return "Foo";
}

I call this method like this:

var x = Get().Result;

Description of other method

internal async static Task<SqlConnection> InitializeConnection()
{
        SqlConnection sc;
        sc = new SqlConnection();            
        sc.ConnectionString = @"Data Source=.\MSSQL;Initial Catalog=MyDB;Integrated Security=True;Async=True";                                  
         await sc.OpenAsync();//on this line the program long waits and doesn't connect

        return sc;
    }  

I checked with different correct lines of connection without use of asynchrony and everything worked. How to fix it ? Thank you.

1 Answer 1

2

You are probably causing a deadlock by using Result. You should use await instead.

I explain this deadlock in detail on my blog. In essence, there are many contexts (such as UI or ASP.NET contexts) that only permit a single thread to execute at a time. By default, await will capture a context and resume the rest of the async method in that context. So, by (synchronously) blocking a thread in that context by calling Result, you are preventing the async method from completing.

Sign up to request clarification or add additional context in comments.

2 Comments

I specified "await Get ()", but now as a result I receive the line "System.Threading.Tasks.Task ' 1 [System.String]".
Sounds like you're using MVC 3? On ASP.NET, you must use .NET 4.5 and set your targetFramework to 4.5 in your web.config.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.