c# - Simple semaphore implementation with form application -


i want show example application of semaphores specific problem homework. added 3 buttons c# form , want show 1 button @ specific time executes bank account function in code. when click 3 buttons in 2 seconds, bank account function must run 1 time. because have thread.sleep(6000) 6 seconds wait in bank account function. 3 of click runs 6 second intervals consecutively. how can change code run 1 time when press 3 buttons consecutively. code is:

namespace semafor_form

{

public partial class form1 : form     {    semaphore semafor=new semaphore(1,1);     delegate void settextcallback(string text);     private void settext(string text)    {         if (this.textbox2.invokerequired)        {            settextcallback d = new settextcallback(settext);            this.invoke(d, new object[] { text });        }        else        {            this.textbox2.text = text;        }    }        public form1()     {         initializecomponent();      }      private void form1_load(object sender, eventargs e)     {      }      private void bankaccount()     {        semafor.waitone();        double = convert.todouble (textbox1.text) + convert.todouble (textbox2.text);        thread.sleep(6000);        semafor.release();         settext(a.tostring());       }      private void btnatm_click(object sender, eventargs e)     {         thread t = new thread(new threadstart(bankaccount));         t.start();      }      private void btncounter_click(object sender, eventargs e)     {          thread t = new thread(new threadstart(bankaccount));         t.start();     }      private void btnint_click(object sender, eventargs e)     {          thread t = new thread(new threadstart(bankaccount));         t.start();     }  }    

}

i may have misread question. don't want buttons when thread being used? (so you'll miss transactions?)

try this:

private void bankaccount() {    if (semafor.waitone(0))    {        double = convert.todouble (textbox1.text) + convert.todouble (textbox2.text);        thread.sleep(6000);        semafor.release();         settext(a.tostring());     }  } 

try changing semaphore semafor=new semaphore(1,1); semaphore semafor=new semaphore(0,1);

you initializing new semaphore without ever releasing it.


Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -