2016 MacBook Pro shutdowns when the lid is close with cause 0
Possible hardware issues aside, check what is your setting on what the computer wants to do when you close the lid and the behaviour afterwards. You can see the settings with the:

pmset -g


Look for the hibernatemode, autopoweroffdelay and standbydelay settings.

See a blog post describing the pmset settings here

On the hardware problems side I've read reports that a faulty charger might cause the MacBook to shutdown. As you report that the problem does not occur when on battery life, this may be the culprit and I'd suggest you try a different charger.

Is the time you mention "for a while" three hours or more? Then the problem occurs when your MacBook tries to enter the standby (see standbydelay setting above).