2012-11-06 39 views
2

我們需要使用SynchronizationContext通過發送(我們不希望通過'Post'異步)返回一個值(特別是MessageBox DialogResult)。只是不確定的語法。 我們在主窗口後面出現MessageBox問題,這被認爲是由於無法輕易訪問主窗體IWin32Window值而導致的......我們正在使用這個,但說實話,我對它感到不舒服。是否可以使用synchronizationcontext返回一個值.send

DialogResult dr; 
SynchronizationContext synchContext; 

//in main forms constructor 
    { 
     ... 
     synchContext = AsyncOperationManager.SynchronizationContext; 
    } 

void workerThread(object obj, DoWorkEventArgs args) 
{ 

    // SynchronizationContext passed into worker thread via args 
    sc.Send(delegate {dr = MessageBoxEx.Show("Yes or no?", "Continue?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);},null); 
} 

回答

0

您可以將object傳遞給您傳遞給發送的代理。

因此,這裏是我會做什麼:

class DialogResultReference 
{ 
    internal DialogResult DialogResult { get; set; } 
} 
class YourClass 
{ 
    static void ShowMessageBox(object dialogResultReference) 
    { 
     var drr = (DialogResultReference)dialogResultReference; 
     drr.DialogResult = MessageBoxEx.Show("Yes or no?", "Continue?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question); 
    } 

    // ... You just remove dr from the class 
    SynchronizationContext synchContext; 

    //in main forms constructor 
    { 
     ... 
     synchContext = AsyncOperationManager.SynchronizationContext; 
    } 

    void workerThread(object obj, DoWorkEventArgs args) 
    { 
     var drr = new DialogResultReference(); 
     sc.Send(YourClass.ShowMessageBox, drr); 
    } 
} 
相關問題