1

我在使用 Thread.sleep(seconds)时遇到问题,它会暂停我在睡眠状态下的所有执行。但是我尝试了另一种解决方案,也使用 for loop,但是我期望它不起作用。

单击登录按钮时:

  1. 行动报告="关于进展";
  2. 再过 2 秒,它将“尝试连接到数据库”
  3. 然后打开数据库后会像“数据库连接成功”

这是代码:

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
}

请有人帮助我。

4

3 回答 3

3

await(在 C# 5.0 中引入)Task.Delay使这变得非常简单:

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";
}

对于 C# 4.0 解决方案,它有点混乱,但不是很多:

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());
}

这里的关键点是,您绝不会阻塞 UI 线程,您只是让 UI 线程继续处理事件两秒钟,然后再给它做点什么。

于 2013-02-27T20:14:16.647 回答
0

我找到了这样的答案

delay("Try to Connecting the database");

像这样延迟。

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;
    }

谢谢朋友!回复我。

于 2013-03-01T06:08:26.780 回答
-1

您首先需要查找并了解在后台线程上执行处理。主要规则是;

  1. 你永远不应该阻止用户界面
  2. 不要尝试从后台线程与 UI 线程对话
  3. 如果你调用 Thread.Sleep,它可能是错误的

您的问题为您提供了学习新架构模式的机会。这些看起来像不错的候选人;

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

于 2013-02-27T20:15:02.623 回答