首頁 > 後端開發 > C++ > 如何修復'呼叫線程無法訪問此對象,因為一個不同的線程擁有它” WPF中的錯誤?

如何修復'呼叫線程無法訪問此對象,因為一個不同的線程擁有它” WPF中的錯誤?

Barbara Streisand
發布: 2025-02-01 21:46:10
原創
902 人瀏覽過

How to Fix the

在UI更新中,

解決“跨線程操作無效”異常 錯誤“呼叫線程無法訪問此對象,因為不同的線程擁有它”,通常會在嘗試從背景線程修改UI元素時發生。 這是因為UI元素由主線程所有。代碼中的有問題的行是:

此代碼嘗試更新
<code class="language-csharp">objUDMCountryStandards.Country = txtSearchCountry.Text.Trim() != string.Empty ? txtSearchCountry.Text : null;</code>
登入後複製
,它可能與UI(例如,更新文本框)從主線程以外的線程進行交互。

為了解決此問題,您必須將UI更新元使用回到主線程。 這是兩個常見的解決方案:objUDMCountryStandards.Country

方法1:使用

Dispatcher.Invoke> 此方法可確保

委託中的代碼在主線程上運行:

Invoke

<code class="language-csharp">this.Dispatcher.Invoke(() =>
{
    objUDMCountryStandards.Country = txtSearchCountry.Text.Trim() != string.Empty ? txtSearchCountry.Text : null;
});</code>
登入後複製
方法2:使用

Dispatcher.CheckAccess>

此方法首先檢查當前線程是否可以訪問UI。如果確實如此,則更新將直接進行;否則,使用

Dispatcher.Invoke>

<code class="language-csharp">private void GetGridData(object sender, int pageIndex)
{
    Standards.UDMCountryStandards objUDMCountryStandards = new Standards.UDMCountryStandards();
    objUDMCountryStandards.Operation = "SELECT";

    if (Dispatcher.CheckAccess())
    {
        objUDMCountryStandards.Country = txtSearchCountry.Text.Trim() != string.Empty ? txtSearchCountry.Text : null;
    }
    else
    {
        this.Dispatcher.Invoke(() =>
        {
            objUDMCountryStandards.Country = txtSearchCountry.Text.Trim() != string.Empty ? txtSearchCountry.Text : null;
        });
    }

    DataSet dsCountryStandards = objStandardsBusinessLayer.GetCountryStandards(objUDMCountryStandards);
    // ... rest of your code
}</code>
登入後複製
>通過實現這些方法中的任何一種,您可以保證在主線程上執行UI更新,從而防止“跨線程操作”異常並保持UI響應能力。 請記住將佔位符替換為

>和objUDMCountryStandards的佔位符。 txtSearchCountry>

以上是如何修復'呼叫線程無法訪問此對象,因為一個不同的線程擁有它” WPF中的錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板