Sandeep Polavarapu
Sandeep Polavarapu

Reputation: 382

Calling same method asynchronoulsy inside a for loop and catching the result properly

I have a method which checks whether a SQL Server is available or not

public static bool IsServerAvailable(string connection)
    {
        bool isAvailable = false;
        try
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                isAvailable = true;
            }
        }
        catch
        {
            isAvailable = false;
        }
        return isAvailable;
    }

Now i have to write a method which accepts a dictionary having keys as connection strings and update the value depending on the result returned from above method

But the problem is i need to make asynchronous calls and able to do, but facing issues with updating the value of a corresponding conn (key) in dictionary

 public delegate bool CheckConnectionDelegate(string conn);

    public static void CheckCubeAccessibility(Dictionary<ServerName, bool> serverDict)
    {
        string conn;
        //Create the delegate
        CheckConnectionDelegate serverConn = new CheckConnectionDelegate(IsServerAvailable);

        foreach (var server in serverDict)
        {
            switch (server.Key)
            {
                case ServerName.A:
                    conn = "A";
                    break;
                case ServerName.B:
                    conn = "B";
                    break;
                case ServerName.C:
                    conn = "C";
                    break;
            }
            //Call the begin invoke method
            IAsyncResult res = serverConn.BeginInvoke(conn, null, null);

        }

    }

Can any one help me?

solution for the above problem is Writing a lambda expression mentioned at How to get the parameters passed to the asynchronous method in the callback

But i need a solution to delay the function CheckCubeAccessibility return untill all the Async calls are returned

How to do this?

Upvotes: 0

Views: 319

Answers (1)

Adam
Adam

Reputation: 16199

The Dictionary needs to be outside of the function.

You need to do the Async call and have a callback method to another function that then updates the Dictionary.

Change this line to:

  IAsyncResult res = serverConn.BeginInvoke(conn, new AsyncCallback(CallbackMethod), null);

Then create the function:

static void CallbackMethod(IAsyncResult ar)
    {

    }

Then do your updating there.

Read this for more information: Calling Synchronous Methods Asynchronously

Upvotes: 1

Related Questions