Can I detect if my code is executing in an Azure worker role?

前端 未结 5 1913
情深已故
情深已故 2021-01-18 13:24

I have some shared assemblies/projects that are used within Winforms apps, windows services and now Azure worker roles.

Is there any way that I can detect at runtime

5条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-18 14:10

    For anyone interested, thought I would sharehow I implemented, thanks to @Sandrino Di Mattia's answer:

    You can check for the presence of the RoleRoot environment variable (for Cloud Services at least):

    Note that this does NOT cater for a Winforms App as I only actually required it in the end for Services - i.e. detecting between service running as

    • Azure Worker Role
    • Windows Service
    • Console Application

    This is an outline:

    public static class ServiceRunner
    {
        private static bool IsAzureWorker
        { 
            get { return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("RoleRoot")); } 
        }
    
        public static void Run(string[] args)
        {
            if (IsAzureWorker)
            {
                //Running as Azure Worker
            }
            else if (Environment.UserInteractive) //note, this is true for Azure emulator too
            {
                //Running as Console App
            }
            else
            {
                //Running as Windows Service
            }
        }
    }
    

提交回复
热议问题