2015-06-08 39 views
1

是否有某種方式讓異步事件在Async中運行? oncomplete事件是從外部DLL調用的。外部DLL使用異步,我正在創建一個隱藏多線程的包裝。在異步中運行oncomplete事件

我嘗試過使用AutoResetEvents,但是這些卡在WaitOne上,因爲重置AutoResetEvent的oncomplete事件只在函數完成後才運行。

從我可以從外部Dll拾取,對象樹需要同步到主窗體才能正常工作。這會強制一個線程上的所有內容。 GetTag被稱爲GetTag(this)。

protected EventWaitHandle SyncEvent; 
public string GetTag(object syncObject) 
    { 
     string lResult = ""; 
     SyncEvent = new AutoResetEvent(false); 
     XiServer lOPCServer = new XiServer(OPCServer.ServerID, OPCServer.ApplicationName, syncObject); //create local instance of server synced to mainform 
     lOPCServer.Initiate(OnInitiated2, null); //Connect server 
     SyncEvent.WaitOne(); //Wait here for for connect to finish, Freezes here 

     if (ServerTree == null) 
      ServerTree = new ObjectTree(lOPCServer, lOPCServer.ServerInfo.ServerName); 
     DialogResult dlr = ServerTree.ShowDialog(); 
     if (dlr == DialogResult.OK) 
     { 
      lResult = ServerTree.SelectedObject.InstanceId.FullyQualifiedId; 
     } 
     lOPCServer.Dispose(); 
     return lResult; 
    } 
private void OnInitiated2(Exception aError, object asyncState) 
    { 
     if (aError != null) 
     { 
      GlobalException = aError; 
     } 
     SyncEvent.Set();    
    } 

所以總之,有沒有辦法讓代碼等待,直到Initiate被finsihed後?我沒有訪問啓動代碼。

+0

您是否嘗試創建自己的事件/委託? – RononDex

+0

代表函數調用嵌入在dll中。你是否提出創建某種包裝委託? – blackwolfsa

+0

如果對LOPCServer.Initiate的調用沒有阻塞,您可以將剩下的邏輯移到OnInitiated2回調(我猜)。 這就是Initiate調用下面的所有內容都轉到了回調函數。 – matcheek

回答

-1

好吧我在這附近找到了。 我一直檢查應該在啓動函數上最後設置的字段。 在服務器對象我使用的是isConnected場

while ((lOPCServer.IsConnected == false) && (lTimeout < 60000)) //1 min timeout 
{ 
    Thread.Sleep(10); 
    lTimeout += 10; 
} 

if (lTimeout >= 60000) 
{ 
    return ""; //Server initaite timed out 
} 
+0

如果單獨的兩個線程同時調用'GetTag'會怎麼樣?您的服務器將啓動兩次。 – VMAtm

+0

我不認爲我完全理解你的說法。但如果我理解正確。 GetTag從兩個單獨的線程中調用兩次並不重要。它使用的變量都是本地的,服務器可以處理多個併發連接(GetTag已經創建了暫時連接到服務器的第二個連接) – blackwolfsa

+0

好吧,只需澄清一下 – VMAtm