在System.Windows.Forms.Form
,在OnShown
倍率(或Shown
事件處理程序)來完成的CallContext
任何修改,在事件發生後消失。例如,在下面的代碼中,當雙擊表單時,它會顯示'正在啓動!'在它的標題,而數據實際上被修改爲'你好,世界!'當表單被顯示時。更改CallContext中在OnShown處理程序不會保留
如果覆蓋適用於OnLoad
而不是OnShown
,雙擊將顯示消息('Hello,World!')。
...
using System.Runtime.Remoting.Messaging;
...
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
CallContext.SetData("Message", "Starting Up!");
}
public string Message
{
get
{
return CallContext.GetData("Message") as string;
}
}
protected override void OnShown(EventArgs e)
{
CallContext.SetData("Message", "Hello, World!");
base.OnShown(e);
}
protected override void OnDoubleClick(EventArgs e)
{
this.Text = this.Message;
base.OnDoubleClick(e);
}
}
有人可以解釋這種行爲的原因嗎? (或者只是我的電腦,做自己的事?)
此4.6.1(Visual Studio的2015年),在Windows 7 64位系統已嘗試在.Net框架;目標平臺是x86(x64或AnyCPU沒有運氣); [STAThread]
適用於Main()
。
該行爲是正常的。當你使用'Form.BeginInvoke'調用一個方法時,它使用一個捕獲的'ExecutionContext'來運行這個方法,並且在'CallContext'中做出的修改在這之後是不可見的。 如果你看一下'Form'的源代碼,你會看到'OnShown'被調用''OnLoad''(http://referencesource.microsoft.com/)中的'BeginInvoke'調用的'CallShownEvent'方法。 com /#System.Windows.Forms/winforms/Managed/System/WinForms/Form.cs,4906)方法,因此'CallContext'中的更改對於'OnShown'方法是本地的,並且在當前上下文中不可見。 –
@ reza-aghaei明白了;謝謝......這就是答案......我錯過了'OnLoad'末尾的CallShownEvent的'BeginInvoke' ... – Raje