2010-09-22 87 views
0

如果需要調用,我使用此方法courtesy of casperOne來設置表單元素上的屬性值。以線程安全的方式從表單元素中檢索屬性值

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[] { }); 
} 

這工作:

// Set a label's text 
SynchronizedInvoke(lblCurrCalStatus,() => lblCurrCalStatus.Text = "Downloading..."); 

出於顯而易見的原因,這是行不通的:

// Retrieve a label's text 
string calStatus = SynchronizedInvoke(lblCurrCalStatus,() => lblCurrCalStatus.Text); 

是否有類似SynchronizedInvoke可以返回屬性值的函數?這將需要一個通用的返回類型和鑄像這樣:

// Retrieve a label's text 
string calStatus = (string)SynchronizedInvokeReturn(lblCurrCalStatus,() => lblCurrCalStatus.Text); 

回答

0

您可以設置匿名方法裏面的變量值:

string calStatus = string.Empty; 
SynchronizedInvoke(lblCurrCalStatus,() => calStatus = lblCurrCalStatus.Text); 
+0

謝謝,這作品! – Pieter 2010-09-22 12:56:34