Reputation: 165
I have a problem using Thread.sleep(seconds), it pauses all my execution in sleeping state. But I tried another solutions also using for loop, however what I'm expecting it's not working.
When the login button is clicked:
Here is the code:
private void Loginbtn_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if(userText.Text!=String.Empty && passText.Password!=String.Empty){
ProgressForm.Visibility = System.Windows.Visibility.Visible;
LoginForm.Visibility = System.Windows.Visibility.Hidden;
delay(2);
actionReport.Text = "Try to Connecting the database";
String ConnectionString = "server=127.0.0.1;uid=root;pwd='';database=smsdb;";
MySqlConnection con = new MySqlConnection(ConnectionString);
try {
con.Open();
delay(2);
actionReport.Text = "Database Connected Sucessfully";
}
catch(MySqlException sqle){
actionReport.Text = sqle.Message;
}
}
else {
MessageBox.Show("Please enter the user name and password to verify","Notification",MessageBoxButton.OK,MessageBoxImage.Information);
}
}
private void delay(int seconds)
{
for(long i=0;i<seconds*3600; i++){
//empty
}
Please someone help me.
Upvotes: 1
Views: 4143
Reputation: 165
I found answer like this
delay("Try to Connecting the database");
delay like this.
public void delay(string message) {
var frame = new DispatcherFrame();
new Thread((ThreadStart)(() =>
{
Thread.Sleep(TimeSpan.FromSeconds(2));
frame.Continue = false;
})).Start();
Dispatcher.PushFrame(frame);
actionReport.Text=message;
}
Thanks friends! to reply me.
Upvotes: 0
Reputation: 2848
You first need to look up and understand performing processing on a background thread. The main rules being;
Your questions demonstrate an opportunity for you to learn new architectural patterns. These look like good candidates;
http://www.codeproject.com/Articles/99143/BackgroundWorker-Class-Sample-for-Beginners
http://www.codeproject.com/Articles/26148/Beginners-Guide-to-Threading-in-NET-Part-1-of-n
Upvotes: -1
Reputation: 203838
await
(introduced in C# 5.0) with Task.Delay
makes this trivially easy:
public async void Loginbtn_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
actionReport.Text = "Trying to Connecting to the database";
await Task.Delay(2);
actionReport.Text = "Connected";
}
For a C# 4.0 solution it's a tad messier, but not a whole lot:
public async void Loginbtn_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
actionReport.Text = "Trying to Connecting to the database";
Task.Delay(2).ContinueWith(_ =>
{
actionReport.Text = "Connected";
}, CancellationToken.None
, TaskContinuationOptions.None
, TaskScheduler.FromCurrentSynchronizationContext());
}
The key point here is that at no point are you blocking the UI thread, you're simply letting the UI thread continue on processing events for two seconds before giving it something to do.
Upvotes: 3