【问题标题】:how to pause the function until button is clicked如何暂停功能直到单击按钮
【发布时间】:2015-06-06 17:39:42
【问题描述】:

如何使用 Thread / BackgroundWorker / Timer / AutoResetEvent 或其他东西来强制函数 f 等待 / 暂停 / 暂停,直到用户点击按钮。

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

我可以比较它应该像 Console.ReadKey 一样工作,直到获得输入。

【问题讨论】:

  • 为什么不显示消息或做任何你想做的按钮点击?
  • 你倒退了。 按钮被按下时触发函数。
  • 约翰所说的。事件对于这样的代码工作得很好。另外,不要将这样的代码放在构造函数中。例如,请尝试 Form.Load。对于更复杂的情况,await 可能非常强大 - 但大多数时候它应该不是必需的。
  • 重点不是我想一直显示信息。这只是控制点。我需要暂停 f 函数的原因是等待 WebClient.DownloadFile() 函数或通过单击按钮取消它1

标签: c#


【解决方案1】:

只要您需要在单击按钮时使用 WebClient 取消下载,您就可以使用异步下载:

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

【讨论】:

    【解决方案2】:

    我只是这样管理的:
    我创建了后台工作程序,它允许在执行下载功能期间单击按钮。
    f 函数等待下载函数完成(或中断)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-30
      相关资源
      最近更新 更多