如何判断WCF服务是否在主机上运行?

时间:2017-01-27 21:57:43

标签: c# winforms wcf

我有一个自托管WCF服务的C#应用​​程序。我想在应用程序中添加一个按钮单击事件,让用户知道服务是否正在运行/正在托管。有没有办法检测服务是否正在运行/托管?

如果有人想看到它,这里是我用来开始托管服务的代码:

        private static void RunService()
    {
        System.ServiceModel.ServiceHost host = new System.ServiceModel.ServiceHost(typeof(AccountingOperationsService.AccountingOperationsService));
        System.ServiceModel.Description.ServiceDebugBehavior debug = host.Description.Behaviors.Find<System.ServiceModel.Description.ServiceDebugBehavior>();
        // if not found - add behavior with setting turned on 
        if (debug == null)
        {
            host.Description.Behaviors.Add(
                 new System.ServiceModel.Description.ServiceDebugBehavior() { IncludeExceptionDetailInFaults = true });
        }
        else
        {
            // make sure setting is turned ON
            if (!debug.IncludeExceptionDetailInFaults)
            {
                debug.IncludeExceptionDetailInFaults = true;
            }
        }
        try
        {
            host.Open();


        }
        catch (Exception ex)
        {

            string errorMessage = ex.Message + Environment.NewLine;
            errorMessage += ex.StackTrace + Environment.NewLine;

            DevExpress.XtraEditors.XtraMessageBox.Show(errorMessage, "Error Starting Service", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

1 个答案:

答案 0 :(得分:4)

也许,您需要在wcf服务中创建方法Ping

public bool Ping()
{
    return true;
}

并在应用程序调用中Ping

bool itsWork;
try
{
    itsWork = service.Ping();
}
catch(Exception ex){}