ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 여러명의 유저가 있는데, 일정한 주기마다 한번씩 Flag를 true로 하는 코드
    프로그램(C# etc.) 2023. 1. 12. 14:27

    다음은 C#에서 이 작업을 수행하는 방법에 대한 예입니다:

    class Program
    {
        //List of users with a flag indicating if they are active
        static List<User> users = new List<User>(){ 
            new User(){ Name = "User1", IsActive = false },
            new User(){ Name = "User2", IsActive = false },
            new User(){ Name = "User3", IsActive = false }
        };
    
        //A Timer class to activate a user once every hour
        static Timer activateUserTimer = new Timer(3600000);
    
        static void Main(string[] args)
        {
            activateUserTimer.Elapsed += ActivateUser;
            activateUserTimer.Start();
        }
    
        static void ActivateUser(object sender, ElapsedEventArgs e)
        {
            //Get the index of the next user to activate
            int userIndex = GetNextUserIndex();
    
            //Activate the user
            users[userIndex].IsActive = true;
            Console.WriteLine(users[userIndex].Name + " activated!");
    
            //Deactivate all the other users
            for(int i = 0; i < users.Count; i++)
            {
                if(i == userIndex)
                    continue;
                users[i].IsActive = false;
            }
        }
    
        static int GetNextUserIndex()
        {
            //Find the first inactive user
            int nextUserIndex = users.FindIndex(user => !user.IsActive);
    
            //If all users are active, set the first user as inactive
            if(nextUserIndex == -1)
            {
                nextUserIndex = 0;
                users[nextUserIndex].IsActive = false;
            }
    
            return nextUserIndex;
        }
    }
    
    class User
    {
        public string Name { get; set; }
        public bool IsActive { get; set; }
    }

    이 코드는 활성화 여부를 나타내는 플래그가 있는 사용자 목록을 만듭니다. 그런 다음 Activate User 기능을 활성화하여 한 시간에 한 번씩 사용자 중 한 명을 활성화하는 타이머 개체를 만듭니다.
    이 함수는 GetNextUserIndex 함수를 사용하여 활성화되지 않은 다음 사용자를 가져오고 활성화한 다음 목록의 다른 모든 사용자를 비활성화합니다.
    활성화된 사용자의 이름이 콘솔에 인쇄됩니다.
    타이머 클래스 생성자에 전달되는 밀리초 수를 변경하여 타이머 간격(현재 1시간)을 조정할 수 있습니다.
    목록에서 원하는 수의 사용자를 추가하거나 제거할 수 있습니다.

    이 예에서는 시스템을 사용합니다.Timers.Timer 클래스. System과는 별도의 클래스입니다.스레딩.타이머 클래스, 경과 이벤트 발생

     

    Q2. Thread 안에서만 사용하도록 코드 정리해줘
     
     
    지난번 답변이 잘못되어 죄송합니다. 한 번에 하나씩 사용자를 활성화하고 매 시간마다 나머지 사용자를 비활성화하는 것은 간단하지 않으며 각 사용자가 활성화해야 하는 시간과 모든 사용자가 활성화되었을 때 발생해야 하는 작업과 같은 추가 정보가 필요하다. 다음은 이러한 작업을 수행할 수 있는 방법에 대한 아이디어입니다:
     
    class Program
    {
        //List of users with a flag indicating if they are active
        static List<User> users = new List<User>(){ 
            new User(){ Name = "User1", IsActive = false },
            new User(){ Name = "User2", IsActive = false },
            new User(){ Name = "User3", IsActive = false }
        };
    
        static void Main(string[] args)
        {
            //Create and start a new thread to activate users every hour
            Thread activateUserThread = new Thread(ActivateUsersThread);
            activateUserThread.Start();
        }
    
        static void ActivateUsersThread()
        {
            while(true)
            {
                //Activate a user once every hour
                Thread.Sleep(3600000);
                ActivateUser();
            }
        }
    
        static void ActivateUser()
        {
            //Get the index of the next user to activate
            int userIndex = GetNextUserIndex();
    
            //Activate the user
            lock(users)
            {
                users[userIndex].IsActive = true;
                Console.WriteLine(users[userIndex].Name + " activated!");
            }
        }
    
        static int GetNextUserIndex()
        {
            //Find the first inactive user
            int nextUserIndex;
            lock(users)
            {
                nextUserIndex = users.FindIndex(user => !user.IsActive);
    
                //If all users are active, set the first user as inactive
                if(nextUserIndex == -1)
                {
                    nextUserIndex = 0;
                    users[nextUserIndex].IsActive = false;
                }
            }
            return nextUserIndex;
        }
    }
     
    이렇게 하면 스레드가 매 시간 실행되고 한 번에 한 사용자를 활성화하지만 다른 사용자는 비활성화하지 않습니다.

    제가 이것을 더 도와드릴 수 있다면 알려주세요.

     
     
Designed by Tistory.