views:

37

answers:

0

I've never had much to do with async callbacks and delegates before on WinForms (i.e., not AJAX) so I'm hoping someone can help me out with what I'm trying to do here.

I'm logging into a third-party service over the web. The Login() method is of type Void.

Because this can take up to 10 seconds (very occasionally longer) I want to do this in a new thread. However, I want to know the result from this thread.

The result is based upon whether the Login() method took longer than timeout.

I currently have it working to the point where I can call Login() in its own thread, but I want to add the following two features and despite having spent several hours, still need help:

  1. Implement a timeout in case Login() doesn't respond in a timely manner.
  2. Fire an event in the main thread.

Here's the code I have so far. You can see that I've got something in here concerning an IAsycnResult, but I'm not sure what. I'd be very appreciative of any suggestions on how to achieve those two requests above.

    private static WebClient wc;
    delegate void DelegateConnect();
    private static IAsyncResult IsConnected;

    public Form1()
    {
        InitializeComponent();

        wc = new WebClient();

        ExecuteConnect();
    }

    public static void ExecuteConnect()
    {
        var delConn = new DelegateConnect(Connect);
        IsConnected = delConn.BeginInvoke(new AsyncCallback(Connected), delConn);
    }

    protected static void Connect()
    {
        try
        {
            if (wc != null)
                wc.LogOn(Username, Password);
        }

        catch (Exception)
        {
            MessageBox.Show("Unable to connect.", "Connection status", MessageBoxButtons.OK);
        }
    }

    public static void Connected(IAsyncResult iar)
    {
        var delConn = (DelegateConnect)iar.AsyncState;
        delConn.EndInvoke(iar);
    }