C# WebClient.DownloadDataAsync正在冻结我的UI

C# WebClient.DownloadDataAsync正在冻结我的UI,c#,.net,webclient,C#,.net,Webclient,在我的表单构造函数中,InitializeComponent之后有以下代码: using (WebClient client = new WebClient()) { client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted); client.DownloadDataAsync("http://example.com/version.txt"

在我的表单构造函数中,InitializeComponent之后有以下代码:

using (WebClient client = new WebClient())
{
    client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
    client.DownloadDataAsync("http://example.com/version.txt");
}
当我启动表单时,用户界面直到客户端下载数据完成后才会出现。 client_DownloadDataCompleted方法为空,因此没有问题

我做错了什么? 如何在不冻结UI的情况下执行此操作

谢谢您抽出时间。
致以最良好的祝愿

完整代码:

Program.cs

using System;
using System.Windows.Forms;

namespace Lala
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}
using System;
using System.Net;
using System.Windows.Forms;

namespace Lala
{
    public partial class Form1 : Form
    {
        WebClient client = new WebClient();

        public Form1()
        {
            client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
            client.DownloadDataAsync(new Uri("http://www.google.com"));
            InitializeComponent();
        }

        void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            textBox1.Text += "A";
        }
    }

    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(12, 12);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "button1";
            this.button1.UseVisualStyleBackColor = true;
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(12, 41);
            this.textBox1.Multiline = true;
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(468, 213);
            this.textBox1.TabIndex = 1;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(492, 266);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.TextBox textBox1;
    }
}
使用系统;
使用System.Windows.Forms;
名称空间拉拉
{
静态类程序
{
/// 
///应用程序的主要入口点。
/// 
[状态线程]
静态void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(新Form1());
}
}
}
Form1.cs

using System;
using System.Windows.Forms;

namespace Lala
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}
using System;
using System.Net;
using System.Windows.Forms;

namespace Lala
{
    public partial class Form1 : Form
    {
        WebClient client = new WebClient();

        public Form1()
        {
            client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
            client.DownloadDataAsync(new Uri("http://www.google.com"));
            InitializeComponent();
        }

        void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            textBox1.Text += "A";
        }
    }

    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(12, 12);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "button1";
            this.button1.UseVisualStyleBackColor = true;
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(12, 41);
            this.textBox1.Multiline = true;
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(468, 213);
            this.textBox1.TabIndex = 1;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(492, 266);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.TextBox textBox1;
    }
}
使用系统;
Net系统;
使用System.Windows.Forms;
名称空间拉拉
{
公共部分类Form1:Form
{
WebClient客户端=新的WebClient();
公共表格1()
{
client.DownloadDataCompleted+=新的DownloadDataCompletedEventHandler(client\u DownloadDataCompleted);
client.DownloadDataAsync(新Uri(“http://www.google.com"));
初始化组件();
}
无效客户端\u DownloadDataCompleted(对象发送方,DownloadDataCompletedEventArgs e)
{
textBox1.Text+=“A”;
}
}
部分类Form1
{
/// 
///必需的设计器变量。
/// 
private System.ComponentModel.IContainer components=null;
/// 
///清理所有正在使用的资源。
/// 
///如果应释放托管资源,则为true;否则为false。
受保护的覆盖无效处置(布尔处置)
{
if(处理和(组件!=null))
{
组件。Dispose();
}
基地。处置(处置);
}
#区域Windows窗体设计器生成的代码
/// 
///设计器支持所需的方法-不修改
///此方法的内容与代码编辑器一起使用。
/// 
私有void InitializeComponent()
{
this.button1=new System.Windows.Forms.Button();
this.textBox1=new System.Windows.Forms.TextBox();
这个.SuspendLayout();
// 
//按钮1
// 
this.button1.Location=新系统图纸点(12,12);
this.button1.Name=“button1”;
this.button1.Size=新系统图纸尺寸(75,23);
this.button1.TabIndex=0;
this.button1.Text=“button1”;
this.button1.UseVisualStyleBackColor=true;
// 
//文本框1
// 
this.textBox1.Location=新系统.图纸.点(12,41);
this.textBox1.Multiline=true;
this.textBox1.Name=“textBox1”;
this.textBox1.Size=新系统.Drawing.Size(468213);
this.textBox1.TabIndex=1;
// 
//表格1
// 
此.AutoScaleDimensions=新系统.Drawing.SizeF(6F,13F);
this.AutoScaleMode=System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize=新系统.Drawing.Size(492266);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button1);
this.Name=“Form1”;
this.Text=“Form1”;
此选项为.resume布局(false);
这个。执行布局();
}
#端区
private System.Windows.Forms.Button按钮1;
private System.Windows.Forms.TextBox textBox1;
}
}

如果要在不同的线程中运行下载,请参阅作为起点。

我已经尝试了您的代码,效果很好

运行此操作时,能否发布Main(Args[])方法以及a和b的值:

    int a, b;
    ThreadPool.GetMaxThreads(out a, out b);
我在.NET3.5和VS2008中试用过。我有点不知所措,但我确信这与您机器上的设置有关。不是代码。检查以下内容:

  • 检查线程池(上图)。我得到a=250,b=1000
  • 禁用所有第三方插件
  • 加载VS“清洁”(是否重新启动)
  • 关闭尽可能多的程序/服务
  • 检查你的IE配置。我认为该类使用IE代码/设置
  • 防火墙?杀毒软件
  • 在另一台电脑上试试

    • 我觉得这有点奇怪


      请尝试保留WebClient的成员引用,这样您就不会在构造函数中破坏它,可能它正在客户端上阻塞。Dispose()

      取消删除:许多人都像我一样考虑使用块,我已确认它与此无关


      能否删除using块,我认为它正在等待处置webclient实例。

      我强烈怀疑这与处置webclient有关,而您仍在使用它进行异步调用

      请尝试删除using语句,并改为在事件处理程序中调用Dispose。(或者只是为了测试,根本不用担心如何处理它

      如果您可以发布一个演示此问题的示例,这将非常方便。

      using()语句正在尝试在WebClient仍在下载时调用其Dispose()。Dispose方法可能会等待下载完成后再继续


      尝试不使用using()语句,并在DownloadDataCompleted事件中处理WebClient。

      以及处理其他人提到的可能仍在运行异步调用的内容,我强烈建议不要在窗体的构造函数中执行类似的重量级操作

      改为在OnLoad覆盖中执行此操作,您还可以检查DesignMode属性,这将帮助您避免VS表单出现多个级别的麻烦