C# - 在执行下一个任务之前等待2秒

时间:2018-03-11 11:44:33

标签: c# visual-studio

input_data <- read.csv("input.csv", header= TRUE)
head(input_data)

library("forecast")
library("DBI")
library("RPostgreSQL")
library("lubridate")
Products = unique(input_data["Server.Name"][,])
output = matrix(0,nrow=(length(Products)*(1)),ncol=7)
colnames(output) =

  c(
    "Product",
    "DATE",
    "Forecast",
    "Lo_80",
    "Hi_80 ",
    "Lo_95",
    "Hi_95"
  )

for (i in Products) {

 train = head(input_data["PERCENT_USED"][input_data["Server.Name"]==i] , 90)

  train     = ts(train[1:(length(train))])

  fc1 = auto.arima(train)
  pred1 = forecast( fc1) 
  fit1_acry   = accuracy(pred1)
  fc2 = ets(train)  
  pred2 = forecast( fc2 )
  fit2_acry = accuracy(pred2 )

  MAPE = data.frame ( fit1_MAPE = fit1_acry[,'MAPE'], 
                       fit2_MAPE = fit2_acry[,'MAPE']
  )

  best =  which.min(MAPE)

  BestModel = get(paste('fc',best,sep="")) 

  forecastoutput = data.frame(forecast(BestModel, h=1)) 
  forecast_date = tail(input_data["DATE"][input_data["Server.Name"]==i],1)
  row_index = which(Products==i)

  output[row_index,1]   = i
  output[row_index,2]   = forecast_date
  output[row_index,3]   = (round(forecastoutput$Point.Forecast,2))
  output[row_index,4]   = as.numeric(round(forecastoutput$Lo.80,2))
  output[row_index,5]   = as.numeric(round(forecastoutput$Hi.80,2))
  output[row_index,6]   = as.numeric(round(forecastoutput$Lo.95,2))
  output[row_index,7] = as.numeric(round(forecastoutput$Hi.95,2))
  output_onestep = data.frame(output)

}
output_onestep

嗨,我的代码在上面。我需要按钮的文本更改2秒然后更改回原始文本。这怎么可能?

谢谢, 添

4 个答案:

答案 0 :(得分:3)

像这样实施

private async Task DelayTask()
    {
        await Task.Delay(2000); //2000 = 2sec
        DoyourStuffHere();
        materialRaisedButton16.Text = "Click to kill process";
    }

并称之为

     private void materialRaisedButton16_Click(object sender, EventArgs e)
    {
    foreach (var process in Process.GetProcessesByName("RobloxPlayerBeta"))
    {
        process.Kill();
    }

    materialRaisedButton16.Text = "Successfully killed process!";

    // sleep for 2s WITHOUT freezing GUI

    Task taketime = this.DelayTask();
    }

答案 1 :(得分:2)

不冻结GUI需要某种形式的Mutlitasking。可能甚至是多线程。非常严格地说,调用一堆辅助进程已经是多线程的一种原始形式。可能是最古老的一个,我们发明的就像我们在当时从合作多任务中脱颖而出一样。

您有很多选项可以在.NET Async中进行多任务处理(包含多线程)...等待。任务。线程。对于多线程的初学者,我会建议BackgroundWorker。几年前我写了这个小介绍的例子,经常链接:

#region Primenumbers
private void btnPrimStart_Click(object sender, EventArgs e)
{
    if (!bgwPrim.IsBusy)
    {
        //Prepare ProgressBar and Textbox
        int temp = (int)nudPrim.Value;
        pgbPrim.Maximum = temp;
        tbPrim.Text = "";

        //Start processing
        bgwPrim.RunWorkerAsync(temp);
    }
}

private void btnPrimCancel_Click(object sender, EventArgs e)
{
    if (bgwPrim.IsBusy)
    {
        bgwPrim.CancelAsync();
    }
}

private void bgwPrim_DoWork(object sender, DoWorkEventArgs e)
{
    int highestToCheck = (int)e.Argument;
    //Get a reference to the BackgroundWorker running this code
    //for Progress Updates and Cancelation checking
    BackgroundWorker thisWorker = (BackgroundWorker)sender;

    //Create the list that stores the results and is returned by DoWork
    List<int> Primes = new List<int>();


    //Check all uneven numbers between 1 and whatever the user choose as upper limit
    for(int PrimeCandidate=1; PrimeCandidate < highestToCheck; PrimeCandidate+=2)
    {
        //Report progress
        thisWorker.ReportProgress(PrimeCandidate);
        bool isNoPrime = false;

        //Check if the Cancelation was requested during the last loop
        if (thisWorker.CancellationPending)
        {
            //Tell the Backgroundworker you are canceling and exit the for-loop
            e.Cancel = true;
            break;
        }

        //Determin if this is a Prime Number
        for (int j = 3; j < PrimeCandidate && !isNoPrime; j += 2)
        {
            if (PrimeCandidate % j == 0)
                isNoPrime = true;
        }

        if (!isNoPrime)
            Primes.Add(PrimeCandidate);
    }

    //Tell the progress bar you are finished
    thisWorker.ReportProgress(highestToCheck);

    //Save Return Value
    e.Result = Primes.ToArray();
}

private void bgwPrim_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    pgbPrim.Value = e.ProgressPercentage;
}

private void bgwPrim_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    pgbPrim.Value = pgbPrim.Maximum;
    this.Refresh();

    if (!e.Cancelled && e.Error == null)
    {
        //Show the Result
        int[] Primes = (int[])e.Result;

        StringBuilder sbOutput = new StringBuilder();

        foreach (int Prim in Primes)
        {
            sbOutput.Append(Prim.ToString() + Environment.NewLine);
        }

        tbPrim.Text = sbOutput.ToString();
    }
    else 
    {
        tbPrim.Text = "Operation canceled by user or Exception";
    }
}
#endregion

当然在你的情况下,更简单的东西可以工作:一个基线计时器。你真正想要的只是2秒的延迟?将TImer设置为2秒,不重复,在&#34; materialRaisedButton16_Click&#34;中启动它。让它剔除其余部分。所有真正的多线程实际上都允许您以稍微更易读的形式编写相同的东西(对性能进行一些权衡)。

答案 2 :(得分:1)

最简单的方法是:

 foreach (var process in Process.GetProcessesByName("RobloxPlayerBeta"))
        {
            process.Kill();
        }

        materialRaisedButton16.Text = "Successfully killed process!";

        // sleep for 2s WITHOUT freezing GUI

        Task.Delay(2000).ContinueWith(()=>{
                materialRaisedButton16.Text = "Click to kill process";
          }, TaskScheduler.FromCurrentSynchronizationContext()); // this is to make it run in the UI thread again

答案 3 :(得分:-1)

您可以使用Timer. 在其tick事件中,您将按钮的文本更新回您需要的值。