在UI更新中,
解決“跨線程操作無效”異常 錯誤“呼叫線程無法訪問此對象,因為不同的線程擁有它”,通常會在嘗試從背景線程修改UI元素時發生。 這是因為UI元素由主線程所有。代碼中的有問題的行是:
此代碼嘗試更新
<code class="language-csharp">objUDMCountryStandards.Country = txtSearchCountry.Text.Trim() != string.Empty ? txtSearchCountry.Text : null;</code>
為了解決此問題,您必須將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>
Dispatcher.CheckAccess
>
: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>
>和objUDMCountryStandards
的佔位符。 txtSearchCountry
>
以上是如何修復'呼叫線程無法訪問此對象,因為一個不同的線程擁有它” WPF中的錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!