Threads
Below example will put down to sleep Your thread. This means You are unable to do anything else during that time, if Your application is single threated.
Code that sleep the thread is:
System.Threading.Thread.Sleep(1000); //time in ms, 1 sec
Comment by @EpicSam: This will make your program unresponsive during the sleep. In case you have some sort of user interface that needs to be responsive, consider using line below instead:
await Task.Delay(5000);
In example, it should looks like:
bool Scan(string filePath){
Scanner.Scan(filePath);
var result = Scanner.CheckStatus();
while(result != ResultType.Positive)
{
System.Threading.Thread.Sleep(5000); //time in ms
result = Scanner.CheckStatus();
}
return result
}
Simplified:
bool Scan(string filePath){
Scanner.Scan(filePath);
ResultType result;
while((result = Scanner.CheckStatus()) != ResultType.Positive)
System.Threading.Thread.Sleep(5000); //time in ms
return result
}
Timers & events
Another way to handle the case is use Timers
and Evenets
. You will set up timer, it will do the work each time You want. Once it find the result is done, it will send message to You. This is the correct way, however putting Thread
to Sleep
also works.
Check Comparing Timer with DispatcherTimer to choose which Timer to use.
- Please note that the code below make different results then for Threads -> it does run the whole Scan method in loop. Which includes running the
Scanner.Scan()
method
-
using System.Timers;
public class MyClass
{
Timer mTimer;
string mFilePath;
public delegate void StatusCheck(bool value);
public event StatusCheck StatusChecked;
MyClass(string filePath)
{
mFilePath = filePath;
mTimer = new Timer(); //time in ms
mTimer.Elapsed += new ElapsedEventHandler(Scan);
}
public void Start()
{ mTimer.Enabled=true; }
private void Scan(object source, ElapsedEventArgs e)
{
Scanner.Scan(filePath);
ResultType result;
if(result = Scanner.CheckStatus())
{
this.StatusChecked?.Invoke(result);
}
}
}
Usage will look like:
//some code ...
MyClass checker = new MyClass("C:\a.txt");
checker.StatusChecked += new StatusCheck(myVoid);
checker.Start();
//some more code ..
private void myVoid(bool result)
{
Console.WriteLine("My result is: " + result );
}