Question

I have the following code in my ASP.Net Webforms code-behind in a button click event. There are quite a few other events on the page.

Question is: If Method2 takes longer that the Page life cycle to complete, will my Page life cycle complete and send its html output to the browser? If yes, then what would be the best way to handle this situation - either send updates to UI ( which I have no clue about) or always use Tasks.WaitAll in this situation?

So, when user sees the web form in his/her browser, the thread running Method2 is still in progress. Please note that I have commented out the code that waits for all tasks to complete.

       Task.Factory.StartNew(() =>
            {
                try
                {
                    Method1(); 
                    success1 = true;
                }
                catch (Exception e4)
                {
                    success1 = false;
                    ex = e4.ToString();
                }
            }),
          Task.Factory.StartNew(() =>
                {
                    try
                    {
                        Method2();
                        success2 = true;
                    }
                    catch (Exception e5)
                    {
                        success2 = false;
                        ex = e5.ToString();
                    }
                })

        };
   //Task.WaitAll(tasks);
Was it helpful?

Solution

If Method2 takes longer that the Page life cycle to complete, will my Page life cycle complete and send its html output to the browser?

Yes.

You'll need to ensure that the handler does not finish execution before you are ready for ASP to move on and continue with the page lifecycle process.

You should also avoid the manipulation of shared memory between threads, as you are not doing so in a safe manor.

Rather than setting a success boolean, you can simply cut out all of that code. You can let the exception bubble up and have the main thread check to see that neither task threw an exception instead. When doing that, the TPL will ensure proper synchronization of the data shared between threads.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top