开发者

Thread activate with timer int C#

开发者 https://www.devze.com 2023-03-10 06:35 出处:网络
I have a funct开发者_JS百科ion: void foo() { string a=\"f\"; string b=\"t\"; Console.WriteLine(a+b);

I have a funct开发者_JS百科ion:

void foo() 
{
string a="f";
 string b="t";
 Console.WriteLine(a+b);
}

I also have some int(the functioin know it) that is the number of minutes to activate the function (lets call it COUNT). I want to do this function in a thread that will do the initialization part just one time, and then will print a+b every minute until the COUNT will end. I also want that if the "stop" button will pushed i'll stop the thread. how can i do it?


First you create a Timer and set it to fire every minute (60 seconds, 60k ms). Next you add an Event handler to the Elapsed event (using +=). Third, the handler has this signature

static void timer_Elapsed(object sender, ElapsedEventArgs e)

so you get a reference to the timer from the sender parameter.

Fourth, you have a static variable in the handler which counts how many times it fired.

If it reaches the COUNT then you stop the timer form firing again (set its Enabled property to false). You can do this due to step three. If the count is less than COUNT then print what you need to print. If the count is 0 then do the initialization.

Answer to question edit: Have the timer available in the program's class. Then, in the Stop button's event handler set the timer's Enabled property to false.

0

精彩评论

暂无评论...
验证码 换一张
取 消