我有一個屬性返回一個單選框組的選定項。public string P1 { get => CB.SelectedItem as string; }它用于在類的構造函數中調用的異步函數中。async Task F() { var b = P1?.Equals(".........", StringComparison.InvariantCultureIgnoreCase) ?? false; var t1 = callAsync().ContinueWith(x => { if (b) { .../* use x*/... } }); await t2; await t1; //...代碼工作正常。但是,b在很多地方都使用了,所以我為它創建了一個屬性并刪除了局部變量var b = P1?Equals(....。bool b => P1?.Equals(".........", StringComparison.InvariantCultureIgnoreCase) ?? false;async Task F() { var t1 = callAsync().ContinueWith(x => { if (b) { .../* use x*/... } // Exception if F() is called in constructor }); await t2; await t1; //...現在訪問時出現以下錯誤CB.SelectedItem?跨線程操作無效:控件“CB”從創建它的線程以外的線程訪問。更新: 如果不是從構造函數調用,我發現所有代碼都有效。
1 回答

青春有我
TA貢獻1784條經驗 獲得超8個贊
不同之處在于 whenb是一個屬性,它的 getter 是在內部調用的ContinueWith,而那個 getter 訪問CB.SelectedItem
相反,如果您在里面執行getter F(),然后在里面使用結果ContinueWith,它應該在功能上與您的第一個示例相同
async Task F() {
var a = b; //invokes CB.SelectedItem in the UI thread
var t1 = callAsync().ContinueWith(x => {
if (a) { /*... }
});
- 1 回答
- 0 關注
- 127 瀏覽
添加回答
舉報
0/150
提交
取消