0

Is it possible to implement in Button click event two executing one after another methods by timer? Could anyone suggest something?

Sequence as follows:

  • Within button click
  • first method execution
  • some delay (e.g. 3 sec.)
  • second method execution.

thanks in advance!

2
  • Do you mean sleep in few seconds? Commented Jan 15, 2020 at 19:17
  • I mean when button click event acts, there should be executed methods sequence. Method 1 --> delay --> Method2. Also the delay must be customizable. Commented Jan 15, 2020 at 19:19

1 Answer 1

2

Use an async Click event handler with await Task.Delay:

// class member
private TimeSpan clickActionDelay = TimeSpan.FromSeconds(3);

private async void Button_Click(object sender, RoutedEventArgs e)
{
    var button = (Button)sender;
    button.IsEnabled = false;

    firstAction();

    // wait 3 seconds without blocking the UI thread
    await Task.Delay(clickActionDelay);

    secondAction();

    button.IsEnabled = true;
}

private void firstAction()
{
    ...
}

private void secondAction()
{
    ...
}
Sign up to request clarification or add additional context in comments.

9 Comments

Hi Clemens, since the "second part" doesn't work (see my first post here) I'm going to try that in a single Click. Perhaps that is going to be a solution.
Why do you think it doesn't work? Haven't you tried it?
I meant this topic stackoverflow.com/questions/59754158/… where I used two parts PreviewMouseButtonDown and Up.
I know that question, since I wrote the answer. What has it got to do with what you are asking here? The questions are totally different. The first one asks how to disable a Button while a single method is executed, while this one asks how to put a delay between the execution of two methods. Have you at least tried out what I am suggesting here? Are you not observing a delay between the calls of firstAction and secondAction?
The point is that I'm going to combine "button freezing" from previous question and these two methods execution sequence by timer which are also suggested by you, here.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.