How to integrate WinRT asynchronous tasks into existing synchronous libraries?

We have a long-established, very multi-platform code base, which is currently porting to WinRT. One of the problems we are facing is how to handle the WinRT asynchronous style.

For example, we are not sure how to handle operations with asynchronous WinRT files. Not surprisingly, our code API is synchronous. A typical example is our File :: Open function, which tries to open a file and return with success or failure. How can we call WinRT functions and still keep the behavior of our functions the same?

Please note that we are unfortunately limited by legacy: we cannot just go and change the API to become asynchronous.

Thank!

+1
source share
2 answers

I assume that you want to redefine the library to support WinRT applications without changing the API definitions so that existing applications remain compatible.

I think that if you do not include the await keyword when calling the async method, you will not perform the async operation, it should be executed synchronously. But this really does not work if the method returns a value (in my experience).

I use this code to make the file operation synchronous:

IAsyncOperation<string> contentAsync = FileIO.ReadTextAsync(file);
contentAsync.AsTask().Wait();
string content = contentAsync.GetResults();
+6
source

If you want to share your code with a platform that does not support async / await - you are probably better off having a different API for the old platform and a new one with keys such as

#if SILVERLIGHT
#elif NETFX_CORE
#elif WPF
#endif

, API, , , , , . async . , WinRT . , , .

+2

All Articles