Rik's Ramblings

Monday, October 14, 2013

Note to Self -- Synchronizing Async APIs in Windows Store Apps

I don't think Microsoft really wants us to write synchronous code in Windows 8. But it's such a hassle writing lots of async code.

Here's a neat trick I use to make async calls like CreateFileAsync synchronous.



Concurrency::event synchronizer;
  bool isGood = false;
  auto foo = Concurrency::task(folder->CreateFileAsync(ref new String(L"test"), Windows::Storage::CreationCollisionOption::FailIfExists));

  foo.then([&synchronizer, &isGood](Concurrency::tasktask){
    Windows::Storage::StorageFile ^file = nullptr;
    try{
      file = task.get();
      isGood = true;
      OutputDebugStringA("File created\n");
    }
    catch(...)
    {
      OutputDebugStringA("Exception Caught\n");
    }

    synchronizer.set();
  }, Concurrency::task_continuation_context::use_arbitrary());

  synchronizer.wait();

  char str[100];
  sprintf_s(str, "Synchronous return.  file creation %s\n", isGood?"successful":"failed");
  OutputDebugStringA(str);




Shh, don't tell any one, it's our little secret!

0 Comments:

Post a Comment



<< Home