user3586968
user3586968

Reputation: 13

Thread in static constructor not work instantly

I have a static Thread which is responsible for get and update the token from remote api. I want to start that thread in a static constructor like below

using System;
using System.Threading;

namespace StaticConstructor
{
    public class CallBack
    {
        static string _token = "init";
        static Thread _threadUpdateToken;
        static CallBack()
        {
            _threadUpdateToken = new Thread(()=>
            {
                int i = 0;
                while (i < 3)
                {
                    GetTokenFromAPI();
                    Thread.Sleep(1 * 1000);
                    i++;
                }
            });
            _threadUpdateToken.Start();
            Console.WriteLine($"After thread start {DateTime.Now.ToString("hh:mm:ss")}");
            Thread.Sleep(10 * 1000);
            Console.WriteLine($"Static constructor keep running at {DateTime.Now.ToString("hh:mm:ss")}");
            Console.WriteLine($"token = {_token}");
        }

        public static void GetTokenFromAPI()
        {
            //this is for demo purpose
            var rd = new Random();
            _token = rd.Next().ToString();
            Console.WriteLine($"token has been updated as {_token} at {DateTime.Now.ToString("hh:mm:ss")}");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            CallBack cb = new CallBack();
            Console.ReadKey();
        }
    }
}

The output is

After _threadUpdateToken.Start 05:16:15
Static constructor keeps running at 05:16:25
token = init
token has been updated as 1671358759 at 05:16:25
token has been updated as 437230378 at 05:16:26
token has been updated as 1350585644 at 05:16:27

Then my question is:
1. Why thread _threadUpdateToken not start before static Constructor finished? Is that because static Constructor must be finished before any other threads access static variables?
2. What should i do if i dont want to invoke GetTokenFromAPI() directly in static Constructor like

static CallBack()
        {
            GetTokenFromAPI();
        }

Upvotes: 1

Views: 40

Answers (1)

DavidG
DavidG

Reputation: 119036

From the C# docs:

A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

So what is happening here is that your thread will run right up to the point it tries to call the GetTokenFromAPI static method, wait until the static constructor ends and then carry on.

Upvotes: 1

Related Questions