문제

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);
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top