C# Timer, Event with int and string variable

Markus Freitag 3,791 Reputation points
2023-01-19T15:39:00.3733333+00:00

Hello,

I need to trigger an event with two variables from a timer thread. How can I implement this well?

int as error number

string as message

If I throw an exception within the timer, the application hangs.

Thanks for your help!

Event int, string

Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. Reza Aghaei 4,986 Reputation points MVP Volunteer Moderator
    2023-01-19T20:27:11.7266667+00:00

    Assuming you have a Form1 like this:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public void HandleError(int errorCode, string errorMessage)
        {
            this.Text = $"{errorCode}: {errorMessage} - " +
                $"{DateTime.Now.ToLongTimeString()}";
        }
    }
    

    And a Program.cs like this:

    internal static class Program
    {
        public static Form1 MainForm { get; private set; }
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            MainForm = new Form1();
            Application.Run(MainForm);
        }
    }
    

    The following piece of code throws and exception every two seconds, and updates the Text of your main form:

    System.Threading.Timer timer = new System.Threading.Timer(
        (o) =>
        {
            try
            {
                //do something
                int i = 1;
                i = i / (i - 1);
            }
            catch (Exception)
            {
                Program.MainForm?.Invoke(new Action(() =>
                {
                    Program.MainForm.HandleError(1, "Devide by zero");
                }));
            }
        }, null, 0, 2000);
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.