2014-09-12 55 views
0

我有一個WCF服務運行在服務器和Windows應用程序有一個計時器,每隔30秒由WCF檢查數據庫的一些新聞值。獲取ConnectFailure後,如何連接到WCF?

一切都很順利,但如果我的服務器(當WCF運行時)出於某種原因離線或退出,我得到異常System.Reflection.TargetInvocationException或System.Net.WebExceptionStatus.ConnectFailure。

我想要的是,我的計時器每30秒會檢查一次,並且當我的服務器回來時我想重新建立連接。實際上唯一的辦法是關閉並打開WinForm應用程序。

如何在不關閉我的應用的情況下檢查連接是否恢復或重新連接?

public MyClass() 
{ 
proxy = new TaskService.Service1Client(); 
proxy.GetTarefasCompleted += new EventHandler<GetTarefasCompletedEventArgs> 
(proxy_GetTarefasCompleted); 

timer = new System.Threading.Timer(Callback, null, 0, 30000); 

} 
private void Callback(Object state) 
{ 
    timer.Change(30000, Timeout.Infinite); 

    proxy.GetTarefasAsync(Environment.UserDomainName, Environment.UserName); 

} 

void proxy_GetTarefasCompleted(object sender, GetTarefasCompletedEventArgs e) 
{ 
    try 
    { 

     tarefas = e.Result.OrderByDescending(t => t.Id).ToList(); 
     //code code code 

    } 
    catch (Exception ex) 
    { 
    if (ex.GetType().ToString() == "System.Net.WebExceptionStatus.ConnectFailure" || 
     ex.GetType().ToString() == "System.Reflection.TargetInvocationException") 
     { 
        //treat the error 
     } 
    } 
} 

回答

0

if (proxy.State != System.ServiceModel.CommunicationState.Opened) { proxy.Abort(); proxy.Open(); }

我相信這應該做的伎倆。