当前位置: 动力学知识库 > 问答 > 编程问答 >

multithreading - Threading in Winforms, generate HTML report on completion of tasks

问题描述:

I have a Winforms application that schedules some work using a service. The service has a callback that updates the database with the work proceedings.

Now let's say I schedule x work items. After the x work items are all completed, I want to generate an HTML report about the work statistics. I think the only way I can check the work completion of all items is to see their completion statuses in the database.

Can someone tell me how and when I can generate the HTML report? I think I can use a thread to poll the db to see if all work completed and inform UI to generate the report, but don't know how to implement that.

网友答案:

You can use BackgroundWorker component for waiting async task completed. It's easy. First - drag BackgroundWorker from Toolbox to your form.

Second - when you start processing (e.g. on button click event) add following code:

private void button_Click(object sender, EventArgs e)
{
    backgroundWorker1.DoWork += backgroundWorker1_DoWork;    
    backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
    backgroundWorker1.RunWorkerAsync();
}

Next - add to DoWork event handler code that starts processing and polling database:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    // schedule some work
    // poll database
}

And last - add RunWorkerCompleted handler, which will run just after DoWork completed (i.e. all tasks updated their state in database):

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // generate report
}

Thats it. Btw BackgroundWorker could report progress during polling database. Little searching will help you how to do that :)

网友答案:

You can use Task.ContinueWith and Task.Wait

Example: Using Task

Task.ContinueWith: This extends the initial task. Run immediatly after it finishes

Task.Wait You would use this if you are running several task that provide the same result be may do so at different times, i.e. fetching same data from different web services.(Just an example). This will execute as soon as one of the appropriate task successfully finishes.

分享给朋友:
您可能感兴趣的文章:
随机阅读: