running a function in a thread
-
i havea function in my app called CheckStatus. This take no prameters and returna a boolean value as the result. I am using it in a if..else statement like this:
if (CheckStatus() == true) //Do somethins here else //Do something else here
Now what happening is that CheckStatus function takes some time to process and due to this my UI becomes non responsive. How can i acheive the above functionality by putting it in a separate thread. I'm pretty new to using Threading so it'd be great if someone could explain in a bit of detail. Thaks in advance! -
i havea function in my app called CheckStatus. This take no prameters and returna a boolean value as the result. I am using it in a if..else statement like this:
if (CheckStatus() == true) //Do somethins here else //Do something else here
Now what happening is that CheckStatus function takes some time to process and due to this my UI becomes non responsive. How can i acheive the above functionality by putting it in a separate thread. I'm pretty new to using Threading so it'd be great if someone could explain in a bit of detail. Thaks in advance! -
I use to do it like this:
class SomeClass { public Routine1() { // Show "Wait" cursor (hour-glass) System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor; // reset completion flag workDone = false; ThreadStart ts = new ThreadStart(DoWorkWithStatusChecking); Thread t = new Thread(ts); t.Start(); // in this loop we wait for completion and // processing GUI messages. while( ! t.IsDone this.workDone ) { // If you need to prevent user's interaction with GUI // (clicking around, pressing buttons, etc.) // you can pass message filter to Application.DoEvents() System.Windows.Forms.Application.DoEvents(); // following line is here to prevent 100% CPU load // but some people think it's not necessary // i just dont have time to check it, 'cause it works just fine Sleep(0); } } bool workDone = false; void DoWorkWithStatusChecking() { // This is what you want to do after status-checking. if( this.Status ) { } else { } // ... done, set this.workDone = true; } bool CheckStatus() { // ... real status checking here return ( true | false ); } } // end class SomeClass
Note: routine1 is not reenterable and must be guarded by some sort of guard condition in the beginning! got the idea? Alexei.