tags:

views:

57

answers:

2

I have a winforms app, that's locking up during a web service request

I've tried using doEvents to keep the app unlocked, but its still not responsive enough,

How can I get around this locking, so that the app is responsive at all times?

+3  A: 

Do the web service request in a background thread. Be cautious of too many calls to Application.DoEvents().

BobbyShaftoe
Cross-thread operation not valid: Control 'listView_mylist' accessed from a thread other than the thread it was created on
JL
this.Invoke(new MethodInvoker(delegate { listView_mylist.Items[pos].SubItems[5].Text = "success(no cert configured)"; }));
JL
Adding comments for the next guy - who needs the solution
JL
+5  A: 

The best way is simply to do your IO work on another thread, perhaps via BackgroundWorker, or the async methods of WebClient.

See perhaps here. Be sure to use Invoke when talking back to the UI controls (thread affinity); full example:

using System;
using System.Net;
using System.Windows.Forms;
class MyForm : Form
{
    Button btn;
    TextBox txt;
    WebClient client;
    public MyForm()
    {
        btn = new Button();
        btn.Text = "Download";
        txt = new TextBox();
        txt.Multiline = true;
        txt.Dock = DockStyle.Right;
        Controls.Add(btn);
        Controls.Add(txt);
        btn.Click += new EventHandler(btn_Click);
        client = new WebClient();
        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
    }

    void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        Invoke((MethodInvoker)delegate
        {
            if (e.Cancelled) txt.Text = "Cancelled";
            else if (e.Error != null) txt.Text = e.Error.Message;
            else txt.Text = e.Result;
        });
    }

    void btn_Click(object sender, EventArgs e)
    {
        client.DownloadStringAsync(new Uri("http://google.com"));
    }
}
static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new MyForm());
    }
}
Marc Gravell