Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Returning Task from a Windows Runtime Component

DZone's Guide to

Returning Task from a Windows Runtime Component

· Agile Zone
Free Resource

See how three solutions work together to help your teams have the tools they need to deliver quality software quickly. Brought to you in partnership with CA Technologies

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 ;)

Discover how TDM Is Essential To Achieving Quality At Speed For Agile, DevOps, And Continuous Delivery. Brought to you in partnership with CA Technologies

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.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}