Note that there are some explanatory texts on larger screens.

plurals
  1. POIs there a common pattern for initializing object on a background thread?
    text
    copied!<p>I have an object that takes a long time to be initialized. Therefore I the capability to Start Initializing on application startup. Any subsequent calls to methods on the class we need to have a delay mechanism that waits for the class to finish initialization. </p> <p>I have a couple of potential solutions however I am not entirely satisfied with either of them. The first uses Task.Delay in a while loop and the second uses SemaphoreSlim but involves some unnecessary blocking. I feel this must be a fairly common requirement, can anybody provide some advice on how to best manage this? </p> <p>Oh btw, this is a Metro application so we have limited API's</p> <p>Here is the pseudocode:</p> <pre><code>public class ExposeSomeInterestingItems { private InitialisationState _initialised; private readonly SemaphoreSlim _waiter = new SemaphoreSlim(0); public async Task StartInitialize() { if (_initialised == InitialisationState.Initialised) { throw new InvalidOperationException( "Attempted to initialise ActiveTrackDown" + "loads when it is already initialized"); } _initialised = InitialisationState.StartedInitialisation; new TaskFactory().StartNew(async () =&gt; { // This takes some time to load this._interestingItems = InterestingItemsLoader.LoadItems(); _waiter.Release(); _initialised = InitialisationState.Initialised; }); } public InterestingItem GetItem(string id) { DelayUntilLoaded(); DelayUntilLoadedAlternative(); } private async Task DelayUntilLoaded() { if (_initialised == InitialisationState.NotInitialised) { throw new InvalidOperationException("Error " + "occurred attempting to access details on " + "ActiveTrackDownloads before calling initialise"); } while (true) { if (_initialised == InitialisationState.Initialised) { return; } await Task.Delay(300); } } private async Task DelayUntilLoadedAlternative() { if (_initialised == InitialisationState.NotInitialised) { throw new InvalidOperationException( "Error occurred attempting to access details " + "on ActiveTrackDownloads before calling initialise"); } try { await _waiter.WaitAsync(); } finally { _waiter.Release(); } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload