gpt4 book ai didi

Winforms:保持 Winforms 应用解锁的最佳方式?

转载 作者:行者123 更新时间:2023-12-05 01:20:49 28 4
gpt4 key购买 nike

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

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

我怎样才能绕过这个锁定,让应用程序始终响应?

最佳答案

最好的方法是简单地在另一个线程上完成您的 IO 工作,也许通过 BackgroundWorker,或者 WebClient 的异步方法。

也许见here .一定要在与 UI 控件对话时使用 Invoke(线程关联);完整示例:

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());
}
}

关于Winforms:保持 Winforms 应用解锁的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1662294/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com