react-native-windows icon indicating copy to clipboard operation
react-native-windows copied to clipboard

Background process for wpf app is never killed even after packaging server, wpf app, and command line processes are closed

Open lbochenek opened this issue 9 years ago • 18 comments

Environment

  1. npm install --save-dev rnpm-plugin-windows
  2. react-native wpf

Then, specify:

  • Target Platform: WPF
  • Target Platform Version(s): ?
  • Target Device(s): Desktop
  • Development Operating System: Windows
  • Visual Studio Version: VS 2017

Steps to Reproduce

  1. react-native run-wpf: wpf app spins up
  2. close wpf app
  3. close packaging server
  4. if process still running on commandline, ctrl+c the process

Will see a background process for the wpf app on task manager

Expected Behavior

There shouldn't be a background process for the wpf app

Actual Behavior

After closing wpf app, the task for that app transitions in the task manager from Apps to Background Processes.

Even after closing the packaging server and ctrl+c the process in commandline, the background process is still there

lbochenek avatar Oct 25 '17 15:10 lbochenek

cc @pre10der89 @kevinvangelder, I imagine this is because some threads / dispatchers are not being destroyed properly.

rozele avatar Oct 31 '17 15:10 rozele

@rozele Possible (https://github.com/Microsoft/react-native-windows/issues/1148)?

pre10der89 avatar Oct 31 '17 17:10 pre10der89

@matthargett @rozele @digitalinfinity I am also facing exactly same issue. The app process remain in Taskmanager even it is closed. I tried on default Hello World application and it also behaves the same way. Any workaround or plan to fix this issue?

Here is the call stack of thread I see: Here I see ChakraCore is stuck in JsDisposeRuntime on two different threads might be this is causing?

threads

piyush965 avatar May 30 '18 08:05 piyush965

The symbols are not correct in that screen shot. Can you capture a process dump and share that? You can use https://docs.microsoft.com/en-us/sysinternals/downloads/procdump to do this- run procdump -ma to capture all of the memory in the dump file.

digitalinfinity avatar May 30 '18 18:05 digitalinfinity

@digitalinfinity I created dump file but its quite huge around 250 MB. Is there any way to share that? This issue is easily reproducible on any RN WPF application.

piyush965 avatar May 31 '18 06:05 piyush965

Easiest is to probably just post it to OneDrive/Dropbox and share the link

digitalinfinity avatar May 31 '18 17:05 digitalinfinity

The problem is with not calling ReactPage.DisposeAsync when the App exits. However, I recently tried to add this to Playground.Net46 and there seems to be a deadlock in the cleanup process. Still investigating.

rozele avatar May 31 '18 19:05 rozele

For now my workaround is to override onExit method and call Environment.Exit(0) to kill all opened threads and process.

piyush965 avatar Jun 01 '18 09:06 piyush965

@rozele any luck on this?

piyush965 avatar Jun 05 '18 14:06 piyush965

Calling ReactPage.DisposeAsync in OnExit doesn't work is because ShutdownMode of application is default OnLastWindowClose, which close main thread too fast to shutdown react native thread.

on ReactInstanceManager.DetachViewFromInstanceAsync, last line

await rootViewRemovedTask;

will never continue executing.

Fix:

We can manually shutdown react native bridge gracefully after main window closed, then shutdown application explicitly.

In App.xaml: add ShutdownMode="OnExplicitShutdown" on tag.

In App.xaml.cs:

 private void OnCreate(string[] arguments)
{
...
Application.Current.MainWindow = shellWindow;
// add this line: 
shellWindow.Closed += this.OnShellWindowClosed;
...
}

// Add this function:
private async void OnShellWindowClosed(object sender, EventArgs e)
{
    await _reactPage.DisposeAsync();
    Shutdown();
}

tdzl2003 avatar Jun 06 '18 15:06 tdzl2003

Maybe it's better to provide a method 'Dispose()' which shutdown react native without waiting for it's completion.

tdzl2003 avatar Jun 06 '18 15:06 tdzl2003

tdzl2003 proposed fix works for me

faxioman avatar Jun 27 '18 13:06 faxioman

@tdzl2003 I'd be in favor of having a blocking Dispose option in addition to the DisposeAsync method specifically for the shutdown case.

We use ShutdownMode.OnMainWindowClose and override the App.OnExit as follows

protected override async void OnExit(ExitEventArgs e) { this.logger.Info("Application is disposing the react page...);"); await this.reactPage.DisposeAsync().ConfigureAwait(true); this.logger.Info("Application has disposed the react page...");

 base.OnExit(e);

}

This does seem to shutdown all the react modules properly, but execution never seems reach the last two statements in the OnExit method shown above. So we'll never see the "Application has disposed the react page". I tried to figure this out eons ago, but gave up. Didn't understand why execution didn't continued after the await...

pre10der89 avatar Jun 27 '18 15:06 pre10der89

@rozele Any luck in solving the deadlock you mentioned...

As far as I can tell the deadlock is in the ReactInstanceManager.cs in method:

private async Task DetachViewFromInstanceAsync(ReactRootView rootView, IReactInstance reactInstance) { DispatcherHelpers.AssertOnDispatcher();

        // Detaches ReactRootView from instance manager root view list and size change monitoring.
        // This has to complete before unmounting the application.
        // Returns a task to await the completion of the `removeRootView` UIManager call (an effect of
        // unmounting the application) and the release of all dispatcher affined UI objects.
        var rootViewRemovedTask = await reactInstance.GetNativeModule<UIManagerModule>()
            .DetachRootViewAsync(rootView);

        reactInstance.GetJavaScriptModule<AppRegistry>().unmountApplicationComponentAtRootTag(rootView.GetTag());

        **await rootViewRemovedTask;**
    }

Execution is blocked on "await rootViewRemovedTask"

The UIManagerModule.DetachRootViewAsync creates and stores a TaskCompletionSource in the _rootViewCleanupTasks and then returns the taskCompletionSource.Task to the DetachViewFromInstanceAsync which then calls the "unmountApplicationComponentAtRootTag" and awaits on the taskCompletionSource.Task returned by the UIManagerModule.

The unmount causes the UIManagerModuleWrapper to call UIManagerModule.removeRootView, which is responsible for resolving the TaskCompletionSource created in the UIManagerModule.DetachRootViewAsync.

This is SUPPOSED to cause the await rootViewRemovedTask to release, but that never happens.

The UIManagerModule.removeRootView calls into the shared UImplementation.RemoveRootViewAsync, which will call into the (Net46 or UWP) version of UIViewOperationQueue.RemoveRootViewAsync. The Net46 version will enque the remove root view action:

EnqueueOperation(() => _nativeViewHierarchyManager.RemoveRootView(rootViewTag));

This en-queued action is never executed. I'm guessing this is because the Main thread is already blocked. The TaskCompletionSource.SetResult() is executed but the await on the TaskCompletionSource is not returning.

My best guess is that we've lost the async context somewhere in the "jungle" or we are deadlocked on the various contexts: similar to what is described here:

http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html

This article seems to indicate that you should "[not] block on Tasks; use async all the way down." We are definitely blocking on tasks and we are not using async all the way down. Instead, there is a mix of straight Tasks and async/await and TaskCompletionSource.

I don't understand where to fix the deadlock or where it is "exactly".

Commenting out the await rootViewRemovedTask will cause the application to exit (of course :):))

pre10der89 avatar Jul 10 '18 01:07 pre10der89

@Reseul Any thoughts on this issue? I believe that the deadlock on WPF may be related to some work you did with Issue #1737. Note, that #1470 is over nine months old and may have been another cause (e.g. Not calling DisposeAsync), but now it seems to have transitioned into a deadlock as I describe above...

Any thoughts or help would be appreciated

pre10der89 avatar Jul 10 '18 19:07 pre10der89

@pre10der89 I think the async context was lost. I break the program on Visual Studio, the main thread has exited already.

tdzl2003 avatar Jul 12 '18 09:07 tdzl2003

@pre10der89 I'll try to debug/take a look when I have a chance. I couldn't answer earlier since I was on vacation. It's true that WPF Playground never exited for me, so whatever changes I made didn't make any difference. I don't think I have any blocking on tasks in the code (if by that we mean .Wait() ), but there could be some other issue. I'll debug.

reseul avatar Jul 16 '18 22:07 reseul

We are not investing in new features or lower priority bug fixes on vCurrent. The bulk of investment is now in vNext as we prepare to make that the default choice. If this issue is still relevant on the vNext implementation please open a vNext issue. If this issue is of significant severity for a vCurrent app and vNext is not an option, re-open with justification.

ghost avatar Oct 25 '19 21:10 ghost