0

How to use Thread / BackgroundWorker / Timer / AutoResetEvent or something else to force function f to wait / suspend / pause until the button is clicked by user.

public Form1()
{
    InitializeComponent();
    if(f())
        MessageBox.Show("returned");
}

bool b=false;

private void button1_Click(object sender, EventArgs e)
{
    //do something
    b=true;
}

bool f()
{
    //what to put here

    //should be here only after b==true
    return true;
}

I could compare it should work like Console.ReadKey pauses the function until gets the input.

gangus
  • 103
  • 1
  • 7
  • Why not showing the message or doing whatever you want on button click? – Igor Popov Jun 05 '15 at 11:13
  • 5
    You have it backwards. Trigger the function _when_ the button is pushed. – John Saunders Jun 05 '15 at 11:13
  • What John said. Events work just fine for code like this. Also, do not put code like this in the constructor. Try `Form.Load` instead, for example. And for more complex cases, `await` can be pretty powerful - but it shouldn't really be necessary most of the time. – Luaan Jun 05 '15 at 11:18
  • possible duplicate of [Pause/Resume loop in Background worker](http://stackoverflow.com/questions/8359058/pause-resume-loop-in-background-worker) – Dmitry Jun 05 '15 at 11:26
  • the point is not I want to always show message. It's just control point. The reason why i need to pause f function is waiting for WebClient.DownloadFile() function or canceling it by clicking the button1 – gangus Jun 05 '15 at 14:11
  • @user3599362 - And that's the crucial piece of information that you should have included in your question at the start. – Enigmativity Jun 05 '15 at 22:21

2 Answers2

1

As long as all you need is to cancel downloading using WebClient when button is clicked you can just use asynchronous downloading:

private WebClient _webClient;

public Form1()
{
    InitializeComponent();
    _webClient = new WebClient();
    _webClient.DownloadFileCompleted += (s, e) =>
      {
        try
        {
           if (e.Cancelled) 
             return;

           //do something with your file
        }
        finally
        {
          _webClient.Dispose(); 
        }
      };
    _webClient.DownloadFileAsync(...);
}

private void button1_Click(object sender, EventArgs e)
{
    _webClient.CancelAsync();
}
Igor Popov
  • 2,084
  • 16
  • 18
0

I just managed this way:
I created background worker which lets to click button during executing download function.
f function waits until download function is finished (or interrupted).

gangus
  • 103
  • 1
  • 7