【发布时间】:2018-03-18 15:13:57
【问题描述】:
我在 Visual Studio 2017 中创建了一个新的 WinForms 项目。 然后我在 Form1 (screenshot) 中添加了一个按钮和文本框。
代码:
using System;
using System.Net;
using System.Windows.Forms;
namespace TestWinForms
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private delegate void FormDelegate();
private void button1_Click(object sender, EventArgs e)
{
UseWaitCursor = true;
button1.Enabled = false;
BeginInvoke(new FormDelegate(delegate
{
using (WebClient web = new WebClient())
{
web.Encoding = System.Text.Encoding.UTF8;
textBox1.Text = web.DownloadString("https://stackoverflow.com/");
}
UseWaitCursor = false;
button1.Enabled = true;
}));
}
}
}
当我单击 button1 时,窗口光标不会变为 WaitCursor,当我将光标悬停在 ControlBox 按钮上时,它们不会“发光”。简而言之,BeginInvoke() 会暂时阻塞主线程。为什么会发生这种情况,我该如何避免?
【问题讨论】:
-
不,是 DownLoadString() 阻塞了你的 UI。它在 UI 线程上运行。 BeginInvoke() 所做的只是让它在 Click 事件处理程序完成后运行。考虑改用 DownloadStringAsync()。
-
DownloadString()阻止你而不是BeginInvoke()
标签: c# winforms begininvoke