>c#背景线程异常:“跨线程操作无效:控制'...'从其创建的线程以外的线程访问。 >本文解决使用背景线程和UI元素时遇到的常见C#错误:“调用线程无法访问此对象,因为另一个线程拥有它。” 之所以发生这种情况,是因为UI元素通常由主UI线程创建和拥有。 试图从背景线程中修改它们会违反线程安全。
问题:
当背景线程尝试访问或修改主线程上创建的UI元素(例如文本框或其他控件)时,出现了异常。 WPF和其他UI框架强制执行此限制以防止种族条件和数据腐败。
解决方案:使用>
Dispatcher.Invoke
该解决方案涉及使用>方法将UI更新授予主线程。
Dispatcher.Invoke
Dispatcher.Invoke
>示例代码修改:
假设您有一个方法>在背景线程上运行,该线程需要更新一个名为
>的文本框:
GetGridData
txtSearchCountry
>使用
<code class="language-csharp">private void GetGridData(object sender, int pageIndex) { // ... other code ... objUDMCountryStandards.Country = txtSearchCountry.Text.Trim() != string.Empty ? txtSearchCountry.Text : null; // ... more code ... }</code>校正的代码:
Dispatcher.Invoke
<code class="language-csharp">private void GetGridData(object sender, int pageIndex) { // ... other code ... this.Dispatcher.Invoke(() => { objUDMCountryStandards.Country = txtSearchCountry.Text.Trim() != string.Empty ? txtSearchCountry.Text : null; }); // ... more code ... }</code>块,直到委托完成UI线程上的执行。 这保证了线程安全。
Dispatcher.Invoke
>通过使用Dispatcher.Invoke
,现在安全地在主UI线程上执行了分配,以防止例外。 请记住,将此模式应用于从背景线程执行的所有UI元素修改。
以上是为什么我的C#背景线程抛出'调用线程无法访问此对象”?的详细内容。更多信息请关注PHP中文网其他相关文章!