locked
const fields being treated as static fields in async methods - debugger issue RRS feed

  • Question

  • I have the following code that I've used to re-create the issue is the simplest possible form.
      class Program
      {
        static void Main(string[] args)
        {
          var tester = new Tester();
          tester.DoSomeWork();
          tester.DoSomeWorkAsyc();
          Console.ReadLine();
        }
      }
    
      public class Tester
      {
        public const string WEBSITE_URL = "http://www.matlus.com";
    
        public void DoSomeWork()
        {
          var webClient = CreateWebClient();
          webClient.DownloadStringCompleted += (sender, e) => {
            Console.WriteLine(e.Result);
          };
          webClient.DownloadStringAsync(new Uri(WEBSITE_URL));
        }
    
        public async Task DoSomeWorkAsyc()
        {
          var html = await CreateWebClient().DownloadStringTaskAsync(WEBSITE_URL);
          Console.WriteLine(html);
        }
    
        private WebClient CreateWebClient()
        {
          return new WebClient() { CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore) };
        }
      }


    I realize that const is implicitly treated as static, however the debugging experience is not as one expects. I also realize that the debugger has not been updated in this CTP.

    I'm posting this here just to let the various teams know.

    So here is what's happening.

    In the methods DoSomeWork() and DoSomeWorkAsync(), put break points on the lines that contain the WEBSITE_URL. So you should have two breaks points set up.

    Run the app and hover over the const WEBSITE_URL when the debugger stops on those lines.

    In the first case you'll see the hint show you the value.

    In the second case you'll see nothing. Now in the immediate window type in WEBSITE_URL and you'll see the following error:

    Member 'ConsoleApplication1.Tester.WEBSITE_URL' cannot be accessed with an instance reference; qualify it with a type name instead

    And indeed when I type

    ConsoleApplication1.Tester.WEBSITE_URL It works and the immediate window's editor even helps out (but this is normal since const are treated implicitly as static)

    Of course if you change the field declaration to

    public readonly string WEBSITE_URL = "http://www.matlus.com";


    The debugger works as expected.


     


    http://www.matlus.com
    Saturday, November 19, 2011 8:36 PM

Answers