Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 37 additions & 1 deletion dev/WindowsAppRuntime_UniversalBGTaskDLL/Task.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,45 @@ namespace winrt::Microsoft::Windows::ApplicationModel::Background::UniversalBGTa
ApplicationDataContainer localSettings = ApplicationData::Current().LocalSettings();
auto values = localSettings.Values();
auto lookupobj = values.Lookup(lookupStr);

// LocalSettings.Lookup returns S_OK with a null IInspectable when the key is missing.
// Treat this as an orphaned OS task registration: log and unregister so the broker
// stops re-firing it. Returning cleanly is preferred over throwing because thrown
// exceptions are treated as transient by the broker and would be retried indefinitely.
if (!lookupobj)
{
LOG_HR_MSG(
HRESULT_FROM_WIN32(ERROR_NOT_FOUND),
"UniversalBGTask: no CLSID stored in LocalSettings for TaskId='%ls'. Unregistering orphaned task.",
lookupStr.c_str());
try
{
taskInstance.Task().Unregister(true);
}
CATCH_LOG_MSG("UniversalBGTask: failed to unregister orphaned task TaskId='%ls'.", lookupStr.c_str());
return;
}

winrt::guid comClsId = winrt::unbox_value<winrt::guid>(lookupobj);

THROW_IF_FAILED(CoCreateInstance(comClsId, nullptr, CLSCTX_LOCAL_SERVER, winrt::guid_of<winrt::Windows::ApplicationModel::Background::IBackgroundTask>(), winrt::put_abi(m_bgTask)));
// CoCreateInstance can fail when the COM class isn't registered, the stored CLSID is
// GUID_NULL, or the impl doesn't expose IBackgroundTask. Log the HR with the CLSID
// for diagnostics and return; do not unregister, since the failure may be transient.
wchar_t comClsIdStr[40]{};
::StringFromGUID2(comClsId, comClsIdStr, ARRAYSIZE(comClsIdStr));
HRESULT coCreateHr = CoCreateInstance(comClsId, nullptr, CLSCTX_LOCAL_SERVER,
winrt::guid_of<winrt::Windows::ApplicationModel::Background::IBackgroundTask>(),
winrt::put_abi(m_bgTask));
if (FAILED(coCreateHr))
{
LOG_HR_MSG(
coCreateHr,
"UniversalBGTask: CoCreateInstance failed for CLSID=%ls referenced by TaskId='%ls'.",
comClsIdStr,
lookupStr.c_str());
return;
}

m_bgTask.Run(taskInstance);
}
}
Loading