[英]Having trouble with using async and await to change UI in C#
首先,我很抱歉我的英语不好。我最近刚学了 C#,我仍然了解的不多。 我正在连接 C# WinForm 应用程序,但在使用“async”和“await”更改 UI 时遇到问题。 程序构建成功。 调试时,我在“ActiveForm.Size = scrres.Size;”处收到此消息
System.Windows.Forms.dll 中出现“System.InvalidOperationException”类型的异常,但未在用户代码中处理
附加信息:跨线程操作无效:控制 '' 从创建它的线程以外的线程访问。
我想将表单大小更改为与屏幕分辨率相同。 谢谢阅读。
using System;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RandomNoTHPTChuyenBT
{
public partial class ldsc : Form
{
public ldsc()
{
InitializeComponent();
}
Rectangle scrres = Screen.PrimaryScreen.Bounds;
public Rectangle scrresr
{
get
{
return scrres;
}
}
private async void ldsc_Load(object sender, EventArgs e)
{
await Task.Run(() =>
{
if (scrres == new Rectangle(0, 0, 1366, 768))
{
ActiveForm.Size = scrres.Size;
pictureBox2.Size = scrres.Size;
}
if (scrres == new Rectangle(0, 0, 1024, 768))
{
ActiveForm.Size = scrres.Size;
pictureBox2.Size = scrres.Size;
}
});
if (scrres == new Rectangle(0, 0, 1366, 768))
{
pictureBox1.Location = new Point(608, 310);
}
if (scrres == new Rectangle(0, 0, 1024, 768))
{
pictureBox1.Location = new Point(437, 309);
}
}
您已将 UI 代码封装在Task.Run
。 不要那样做。 Task.Run
是将工作卸载到另一个线程。 您不想这样做,而是想在 UI 线程中运行它。
完成后,您就没有什么可await
,因此您可以从方法中删除async
修饰符,因为它是不必要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.