Notitie
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen u aan te melden of de directory te wijzigen.
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen de mappen te wijzigen.
[ Bijgewerkt voor UWP-apps in Windows 10. Zie het archief ] voor windows 8.x-artikelen
Belangrijke API's
Leer hoe u in een afzonderlijke thread werkt door een werkitem naar de threadgroep te verzenden. Gebruik dit om een responsieve gebruikersinterface te onderhouden terwijl u nog steeds werk voltooit dat een merkbare hoeveelheid tijd in beslag neemt en gebruikt om meerdere taken parallel uit te voeren.
Het werkitem maken en verzenden
Maak een werkitem door RunAsync aan te roepen. Geef een gedelegeerde op om het werk uit te voeren (u kunt een lambda of een gedelegeerde functie gebruiken). Houd er rekening mee dat RunAsync een IAsyncAction-object retourneert; sla dit object op voor gebruik in de volgende stap.
Er zijn drie versies van RunAsync beschikbaar, zodat u desgewenst de prioriteit van het werkitem kunt opgeven en kunt bepalen of het gelijktijdig wordt uitgevoerd met andere werkitems.
Opmerking
Gebruik CoreDispatcher.RunAsync om toegang te krijgen tot de UI-thread en de voortgang van het werkitem weer te geven.
In het volgende voorbeeld wordt een werkitem gemaakt en wordt een lambda geleverd om het werk uit te voeren:
// The nth prime number to find.
const uint n = 9999;
// Receives the result.
ulong nthPrime = 0;
// Simulates work by searching for the nth prime number. Uses a
// naive algorithm and counts 2 as the first prime number.
IAsyncAction asyncAction = Windows.System.Threading.ThreadPool.RunAsync(
(workItem) =>
{
uint progress = 0; // For progress reporting.
uint primes = 0; // Number of primes found so far.
ulong i = 2; // Number iterator.
if ((n >= 0) && (n <= 2))
{
nthPrime = n;
return;
}
while (primes < (n - 1))
{
if (workItem.Status == AsyncStatus.Canceled)
{
break;
}
// Go to the next number.
i++;
// Check for prime.
bool prime = true;
for (uint j = 2; j < i; ++j)
{
if ((i % j) == 0)
{
prime = false;
break;
}
};
if (prime)
{
// Found another prime number.
primes++;
// Report progress at every 10 percent.
uint temp = progress;
progress = (uint)(10.0*primes/n);
if (progress != temp)
{
String updateString;
updateString = "Progress to " + n + "th prime: "
+ (10 * progress) + "%\n";
// Update the UI thread with the CoreDispatcher.
CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
CoreDispatcherPriority.High,
new DispatchedHandler(() =>
{
UpdateUI(updateString);
}));
}
}
}
// Return the nth prime number.
nthPrime = i;
});
// A reference to the work item is cached so that we can trigger a
// cancellation when the user presses the Cancel button.
m_workItem = asyncAction;
// The nth prime number to find.
const unsigned int n{ 9999 };
// A shared pointer to the result.
// We use a shared pointer to keep the result alive until the
// work is done.
std::shared_ptr<unsigned long> nthPrime = std::make_shared<unsigned long>(0);
// Simulates work by searching for the nth prime number. Uses a
// naive algorithm and counts 2 as the first prime number.
// A reference to the work item is cached so that we can trigger a
// cancellation when the user presses the Cancel button.
m_workItem = Windows::System::Threading::ThreadPool::RunAsync(
[=, strongThis = get_strong()](Windows::Foundation::IAsyncAction const& workItem)
{
unsigned int progress = 0; // For progress reporting.
unsigned int primes = 0; // Number of primes found so far.
unsigned long int i = 2; // Number iterator.
if ((n >= 0) && (n <= 2))
{
*nthPrime = n;
return;
}
while (primes < (n - 1))
{
if (workItem.Status() == Windows::Foundation::AsyncStatus::Canceled)
{
break;
}
// Go to the next number.
i++;
// Check for prime.
bool prime = true;
for (unsigned int j = 2; j < i; ++j)
{
if ((i % j) == 0)
{
prime = false;
break;
}
};
if (prime)
{
// Found another prime number.
primes++;
// Report progress at every 10 percent.
unsigned int temp = progress;
progress = static_cast<unsigned int>(10.f*primes / n);
if (progress != temp)
{
std::wstringstream updateStream;
updateStream << L"Progress to " << n << L"th prime: " << (10 * progress) << std::endl;
std::wstring updateString = updateStream.str();
// Update the UI thread with the CoreDispatcher.
Windows::ApplicationModel::Core::CoreApplication::MainView().CoreWindow().Dispatcher().RunAsync(
Windows::UI::Core::CoreDispatcherPriority::High,
Windows::UI::Core::DispatchedHandler([=]()
{
strongThis->UpdateUI(updateString);
}));
}
}
}
// Return the nth prime number.
*nthPrime = i;
});
// The nth prime number to find.
const unsigned int n = 9999;
// A shared pointer to the result.
// We use a shared pointer to keep the result alive until the
// work is done.
std::shared_ptr<unsigned long> nthPrime = std::make_shared<unsigned long>(0);
// Simulates work by searching for the nth prime number. Uses a
// naive algorithm and counts 2 as the first prime number.
auto workItem = ref new Windows::System::Threading::WorkItemHandler(
[this, n, nthPrime](IAsyncAction^ workItem)
{
unsigned int progress = 0; // For progress reporting.
unsigned int primes = 0; // Number of primes found so far.
unsigned long int i = 2; // Number iterator.
if ((n >= 0) && (n <= 2))
{
*nthPrime = n;
return;
}
while (primes < (n - 1))
{
if (workItem->Status == AsyncStatus::Canceled)
{
break;
}
// Go to the next number.
i++;
// Check for prime.
bool prime = true;
for (unsigned int j = 2; j < i; ++j)
{
if ((i % j) == 0)
{
prime = false;
break;
}
};
if (prime)
{
// Found another prime number.
primes++;
// Report progress at every 10 percent.
unsigned int temp = progress;
progress = static_cast<unsigned int>(10.f*primes / n);
if (progress != temp)
{
String^ updateString;
updateString = "Progress to " + n + "th prime: "
+ (10 * progress).ToString() + "%\n";
// Update the UI thread with the CoreDispatcher.
CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
CoreDispatcherPriority::High,
ref new DispatchedHandler([this, updateString]()
{
UpdateUI(updateString);
}));
}
}
}
// Return the nth prime number.
*nthPrime = i;
});
auto asyncAction = ThreadPool::RunAsync(workItem);
// A reference to the work item is cached so that we can trigger a
// cancellation when the user presses the Cancel button.
m_workItem = asyncAction;
Na de aanroep van RunAsync, wordt het werkitem in de wachtrij geplaatst door de threadpool en uitgevoerd zodra er een thread beschikbaar is. Werkitems in threadpools worden asynchroon uitgevoerd en ze kunnen in elke volgorde worden uitgevoerd, dus zorg ervoor dat uw werkitems onafhankelijk werken.
Houd er rekening mee dat het werkitem de eigenschap IAsyncInfo.Status controleert en beƫindigd wordt als het werkitem wordt geannuleerd.
Voltooiing van werkitem verwerken
Geef een voltooiingshandler op door de eigenschap IAsyncAction.Completed in te stellen van het werkitem. Geef een gemachtigde op (u kunt een lambda of een gedelegeerdefunctie gebruiken) om de voltooiing van werkitems af te handelen. Gebruik bijvoorbeeld CoreDispatcher.RunAsync om toegang te krijgen tot de UI-thread en het resultaat weer te geven.
In het volgende voorbeeld wordt de gebruikersinterface bijgewerkt met het resultaat van het werkitem dat in stap 1 is ingediend:
asyncAction->Completed = ref new AsyncActionCompletedHandler(
[this, n, nthPrime](IAsyncAction^ asyncInfo, AsyncStatus asyncStatus)
{
if (asyncStatus == AsyncStatus::Canceled)
{
return;
}
String^ updateString;
updateString = "\n" + "The " + n + "th prime number is "
+ (*nthPrime).ToString() + ".\n";
// Update the UI thread with the CoreDispatcher.
CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
CoreDispatcherPriority::High,
ref new DispatchedHandler([this, updateString]()
{
UpdateUI(updateString);
}));
});
m_workItem.Completed(
[=, strongThis = get_strong()](Windows::Foundation::IAsyncAction const& asyncInfo, Windows::Foundation::AsyncStatus const& asyncStatus)
{
if (asyncStatus == Windows::Foundation::AsyncStatus::Canceled)
{
return;
}
std::wstringstream updateStream;
updateStream << std::endl << L"The " << n << L"th prime number is " << *nthPrime << std::endl;
std::wstring updateString = updateStream.str();
// Update the UI thread with the CoreDispatcher.
Windows::ApplicationModel::Core::CoreApplication::MainView().CoreWindow().Dispatcher().RunAsync(
Windows::UI::Core::CoreDispatcherPriority::High,
Windows::UI::Core::DispatchedHandler([=]()
{
strongThis->UpdateUI(updateString);
}));
});
asyncAction.Completed = new AsyncActionCompletedHandler(
(IAsyncAction asyncInfo, AsyncStatus asyncStatus) =>
{
if (asyncStatus == AsyncStatus.Canceled)
{
return;
}
String updateString;
updateString = "\n" + "The " + n + "th prime number is "
+ nthPrime + ".\n";
// Update the UI thread with the CoreDispatcher.
CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
CoreDispatcherPriority.High,
new DispatchedHandler(()=>
{
UpdateUI(updateString);
}));
});
Houd er rekening mee dat de voltooiingshandler controleert of het werkitem is geannuleerd voordat een UI-update werd verzonden.
Samenvatting en volgende stappen
U vindt meer informatie door de code te downloaden uit deze quickstart in het voorbeeld van een ThreadPool-werkitem maken dat is geschreven voor Windows 8.1 en de broncode opnieuw te gebruiken in een win_unap Windows 10-app.