Over a million developers have joined DZone.

Returning Task from a Windows Runtime Component

· Agile Zone

Reduce testing time & get feedback faster through automation. Read the Benefits of Parallel Testing, brought to you in partnership with Sauce Labs.

A very short tip this time, that took me some time to find out.

You will need a Windows Runtime Component if you want, for instance, host a background task in an Universal App. The problem with these components is that you cannot return a Task<T> from a public method. You can use Task<T> inside the component, but not return it to the outside world. If you have a method

public async Task<bool> SomeMethod()
{
  return false; // whatever
}

in your Windows RT component, it won’t even compile. But there is a solution – you can return an IAsyncOperation<T>, and that is awaitable too.

Therefore, I use this simple wrapper to use the method both from inside and outside:

public IAsyncOperation<bool> PublicMethod()
{
  return InternalMethod().AsAsyncOperation();
}

private static Task<bool> InternalMethod()
{
  return false; // whatever
}

And we’re done. This will compile, and you cannot call “await myObject.PublicMethod().

Sometimes code is so easy if you just know how to do it. No sample this time (again) as this is such a small piece of code. If you want to see it running, wait for the next post ;)

The Agile Zone is brought to you in partnership with Sauce Labs. Discover how to optimize your DevOps workflows with our cloud-based automated testing infrastructure.

Topics:

Published at DZone with permission of Joost van Schaik, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}