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

You've been hearing a lot about agile software development, get started with the eBook: Agile Product Development from 321 Gang

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

Download the free agile tools checklist from 321 Gang. This guide will help you choose the right agile tools to position your team for success. 

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}