Be careful when making DataTransferManager.DataRequested an async function
Update: Thanks to Nigel Sampson for correcting my post. :)
This event is fired when a sharing operation starts—typically when the user taps the Share charm, although it is also fired if your app starts a share operation programmatically.
If you use this code, when you are sharing data from your application, you will get a message like one of the following:
“What happened?”, you may ask. Well, there is a trick to making this callback asynchronous.
If we think about the consequences of using async and await, and about the nature of the share operation, we can explain this behavior easily: Once the call to DataRequested returns, it expects the DataRequest to contain the information we want to share. However, if our callback is marked with async and we add a call using await, it will cause the execution flow to leave the function until we are notified by the awaiter that we can continue. DataTransferManager, however, does not know about this and will assume that we have completed the request correctly.
Fortunately, there is a way to tell DataTransferManager to wait for us: using the GetReferral method. Before, we only called it at the end of our callback, to mark the DataRequest as complete. However, if we call it at the beginning we will be able to call asynchronous methods:
Please note that if the asynchronous operations will take more than 200ms you have to use a DataProviderHandler to prevent the operation from timing out.
I hope this helps you.