I'm prototyping an app (UWP console app for now) that is event driven. The app operates on newly created files on the system and I'm using StorageFileQueryResult.ContentsChanged
to watch for them but am unsure what I should be doing to keep the process alive while waiting for the events. I'm currently using an infinite while loop (which works). Surely, there has to be a better way?
I'm using c++/winrt but any general UWP solution be applicable.
Sample code snipped below:
int main()
{
winrt::init_apartment();
Windows::Storage::StorageFolder folder{ Windows::Storage::StorageFolder::GetFolderFromPathAsync(SOME_PATH).get() };
auto queryOptions = Windows::Storage::Search::QueryOptions(Windows::Storage::Search::CommonFileQuery::DefaultQuery, NULL);
auto query = folder.CreateFileQueryWithOptions(queryOptions);
query.ContentsChanged(Query_ContentsChanged);
auto files = query.GetFilesAsync().get();
for (auto const& f : files) {
std::wcout << f.Name().c_str() << std::endl;
}
while (1) {} // Keep process alive
}
Usually, you could use getchar()
or system("pause")
to block the console thread.
Another way you could use is lock, please check the following code:
#include <iostream>
#include <condition_variable>
#include <mutex>
std::condition_variable cv;
std::mutex mtx;
int main()
{
winrt::init_apartment();
std::unique_lock<std::mutex> m(mtx);
Windows::Storage::StorageFolder folder{ Windows::Storage::StorageFolder::GetFolderFromPathAsync(L"C:\\test1").get() };
auto queryOptions = Windows::Storage::Search::QueryOptions(Windows::Storage::Search::CommonFileQuery::DefaultQuery, NULL);
auto query = folder.CreateFileQueryWithOptions(queryOptions);
query.ContentsChanged(Query_ContentsChanged);
auto files = query.GetFilesAsync().get();
cv.wait(m);
//getchar();
//system("pause");
}