Winforms:保持winforms app解锁的最佳方式?

JL.*_*JL. 2 winforms

我有一个winforms应用程序,它在Web服务请求期间锁定

我已经尝试使用doEvents来保持应用程序解锁,但它仍然没有足够的响应,

如何绕过此锁定,以便应用程序始终响应?

Mar*_*ell 5

最好的方法是简单地在另一个线程上执行IO工作,可能是通过BackgroundWorker或者异步方法WebClient.

或许在这里看到.Invoke回到UI控件(线程亲和力)时一定要使用; 完整的例子:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)