在我的應用程序中,我有一個負責所有數據庫操作的類。它從主類中調用,並在操作完成後使用委託來調用方法。 因爲它是異步的,我必須使用調用我的GUI,所以我創建了一個簡單的擴展方法:InvokeRequired和ToolStripStatusLabel
public static void InvokeIfRequired<T>(this T c, Action<T> action)
where T: Control
{
if (c.InvokeRequired)
{
c.Invoke(new Action(() => action(c)));
}
else
{
action(c);
}
}
這工作得很好,當我嘗試調用它的textBox:
textBox1.InvokeIfRequired(c => { c.Text = "it works!"; });
但當我嘗試調用它ToolStripStatusLabel或ToolStripProgressBar我得到一個錯誤:
The type 'System.Windows.Forms.ToolStripStatusLabel' cannot be used as type parameter 'T' in the generic type or method 'SimpleApp.Helpers.InvokeIfRequired(T, System.Action)'. There is no implicit reference conversion from 'System.Windows.Forms.ToolStripStatusLabel' to 'System.Windows.Forms.Control'.
我知道這可能是一個簡單的修補程序,但我能應付自如:/
也許這個類似的問題會幫助你。 http://stackoverflow.com/questions/1127973/how-do-i-make-cross-threaded-calls-to-a-toolstripstatuslabel – Rugbertl