2010-11-05 95 views
2

我使用此函數由Stack Overflow用戶來更新來自BackgroundWorker的控件。InvalidAsynchronousStateException在函數中檢查控件是否需要調用

static void SynchronizedInvoke(ISynchronizeInvoke sync, Action action) 
{ 
    // If the invoke is not required, then invoke here and get out. 
    if (!sync.InvokeRequired) 
    { 
     // Execute action. 
     action(); 

     // Get out. 
     return; 
    } 

    // Marshal to the required thread. 
    sync.Invoke(action, new object[] { }); 
} 

此功能一直運行良好,直到現在。我剛剛得到這個異常:

InvalidAsynchronousStateException

這是什麼意思?如何預防呢?

+0

查看https://stackoverflow.com/a/38411886 – SMUsamaShah 2017-12-12 07:25:18

回答

2

這裏的問題是ISynchronizeInvoke對象綁定到的線程不再存在。例如,如果您生成後臺線程,並且UI線程在後臺任務完成之前退出,則可能會發生這種情況。該線程不再存在,因此沒有任何可以調用的東西,並且你會得到異常。

有沒有好方法來防止這種情況。最好的方法是將Invoke調用包裝爲處理此異常的try/catch

+0

使用[SynchronizationContext](https://stackoverflow.com/a/38411886)可能是更好的選擇。 – SMUsamaShah 2017-12-12 07:24:51

相關問題