带有UI控件的ConfigureAwait(false)? [英] ConfigureAwait(false) with UI controls?

查看:85
本文介绍了带有UI控件的ConfigureAwait(false)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将.ConfigureAwait(false)用于以下两个代码段?

Is it OK to use .ConfigureAwait(false) for the following two code snippets?

案例1

var ds = new BindingSource();
ds.DataSource = await CallAsync(); // .ConfigureAwait(false);
UIControl.DataSource = ds;

案例2

UIControl.DataSource = new BindingSource
{
    DataSource = await CallAsync() // .ConfigureAwait(false)
};

第一个似乎在后台线程上设置UI控件的问题吗?第二个呢?

Does the first one seem to have the problem of set UI control at the background thread? How about the second one?

推荐答案

对控件的所有访问都应在创建控件的同一线程中完成.

All access to controls should be done in the same thread which the control is created.

通过调用

By calling ConfigureAwait(false) you are asking not to attempt to marshal the continuation back to the original context captured. It means the code continue the execution in a different context than the UI thread which is invalid operation.

因此,答案是肯定的,以上两种情况都存在问题,并且会导致:

So, the answer is yes, both above cases have problem and will result in:

InvalidOperationException:跨线程操作无效:从创建该线程的线程之外的其他线程访问控件控件名称".

InvalidOperationException: Cross-thread operation not valid: Control 'Control Name' accessed from a thread other than the thread it was created on.

这篇关于带有UI控件的ConfigureAwait(false)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆