簡體   English   中英

在 C# 中使用 async 和 await 更改 UI 時遇到問題

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM