在c#中需要延迟功能

时间:2013-02-27 20:11:37

标签: c#

我使用 Thread.sleep(秒)时出现问题,它会暂停我在睡眠状态下执行的所有操作。但我尝试了另一种解决方案也使用for循环,但是我期待它不起作用。

单击登录按钮时:

  1. 行动报告=“正在进行中”;
  2. 再过2秒后,它将“尝试连接到数据库”
  3. 然后在打开数据库后,它将像“数据库连接成功”
  4. 以下是代码:

    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
    }
    

    请有人帮帮我。

3 个答案:

答案 0 :(得分:3)

使用await

Task.Delay(在C#5.0中引入)使这很简单:

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线程继续处理事件两秒钟,然后再给它做一些事情。

答案 1 :(得分: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;
    }

谢谢啦! 回复我。

答案 2 :(得分:-1)

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

  1. 你永远不应该阻止UI
  2. 不要尝试从后台线程与UI线程交谈
  3. 如果你调用Thread.Sleep,那可能是错误的
  4. 您的问题表明您有机会学习新的架构模式。这些看起来像是好人选;

    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