簡體   English   中英

異步行為

[英]Async Behaviour

我有以下代碼以異步方式更新進度條,並且通過調用MessageBox注意到了它的異步行為。在這種情況下,它可以正常工作,但是當我睡眠1s(1000)時,MessageBox不會彈出,並且完成進度條將立即填充。 請告知為什么會這樣。

 private void button1_Click(object sender, EventArgs e)
    {
        Update_Async async = new Update_Async(Update_Async_method);
        progressBar1.BeginInvoke(async,10);
        MessageBox.Show("Updation In Progress");


    }

    public void Update_Async_method(int a)
    {
        this.progressBar1.Maximum = a;
        for (int i = 1; i <= a; i++)
        {
            progressBar1.Value = a;
            Thread.Sleep(10);

     //Thread.Sleep(1000);

        }
    }

如果您希望委托Update_Async.BeginInvoke(async, 10)請嘗試使用Update_Async.BeginInvoke(async, 10)但是,您必須在更新進度欄中進行跨線程檢查。


為了回應您的評論,與您已經在做的事情非常相似,

void UpdatingFunction(int value)
{
    if (this.progressBar.InvokeRequired)
    {
        this.progressBar.BeginInvoke(UpdatingFunction, value);
        return;
    }

    // Invoke not required, work on progressbar. 
}

這也解釋了控件上的Invoke方法的用途。

Delegate.BeginInvoke將在線程中運行一次方法,然后將其處置。 如果要在線程中重復執行一些工作並返回中間結果,這是一個糟糕的選擇。 如果這是您想要的,則應使用BackgroundWorker 高度簡短的代碼段:

BackgroundWorker bw;

YourFormConstructor()
{
    ...
    bw = new BackgroundWorker();
    bw.WorkerReportsProgress = true;
    bw.DoWork += BackgroundCalculations;
    bw.ProgressChanged += ShowBackgroundProgress;
}

private void button1_Click(object sender, EventArgs e)
{
  bw.RunWorkerAsync(10);
}

void ShowBackgroundProgress(object sender, ProgressChangedEventArgs e)
{
    this.progressBar.Value = e.ProgressPercentage;
}

static void BackgroundCalculations(object sender, DoWorkEventArgs e)
{
    BackgroundWorker bw = sender as BackgroundWorker;

    int max = (int)e.Argument;
    for (int i = 0; i < max; i++)
    {
        bw.ReportProgress(i * 100 / max);
        Thread.Sleep(10);
    }

    bw.ReportProgress(100);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM