Home TaskCanceledException thread blocking
Reply: 0

TaskCanceledException thread blocking

user45011
1#
user45011 Published in September 19, 2018, 11:14 am

The following function will work sporadically, but most times blocks the thread at await dlScreenshot_task.

Debug.Log("Downloading from Storage...\n" + url); fires for every image url, then Unity deadlocks. Occasionally it will throw a TaskCanceledException. If the task fails in any way, it should return null for that Task.

public async Task<Texture2D> DownloadScreenshotFromStorageAsync(string url)
{
    byte[] screenshotBytes;
    //Firebase.Storage
    StorageReference cloud = _firebaseStorage.GetReferenceFromUrl(_storageBucketURL + url);
    if( cloud != null ) {
        Task<byte[]> dlScreenshot_task = cloud.GetBytesAsync(1920 * 1080);
        Debug.Log("Downloading from Storage...\n" + url);

        try {    
            screenshotBytes = await dlScreenshot_task;

            if( screenshotBytes != null ) {
                Debug.Log("DLed: " + url);
                return MetaLoader.DeserializeImage(screenshotBytes);
            }
            else {
                return null;
            }
        }
        catch(AggregateException aex ) {
            StorageException store_ex = aex.InnerException as StorageException;
            if(store_ex != null ) { Debug.Log("Storage Exception " + store_ex.ErrorCode); }
            return null;
        }
        catch(TaskCanceledException t ) {
            Debug.LogWarning(t);
            return null;
        }
    }
    else {
        Debug.Log("Cloud Storage Reference failed for " + _storageBucketURL + url);
        return null;
    }
}  

The calling function, using interleaving as found in MSDN Docs regarding Task-based async programming:

private async void DisplayScreenshotsFromDB()
{
    Task<List<string>> dl_task = DownloadURLsAsync();

    List<string> screenshotURLs = await dl_task;

    //Interleaved image downloading
    //https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/consuming-the-task-based-asynchronous-pattern
    List<Task<Texture2D>> imageTasks =
                    (from imageUrl in screenshotURLs select DownloadScreenshotFromStorageAsync(imageUrl)).ToList();
    while( imageTasks.Count > 0 ) {
        Task<Texture2D> imageTask = await Task.WhenAny(imageTasks);
        try {
            imageTasks.Remove(imageTask);

            Texture2D image = await imageTask;
            DisplayScreenshot(image);
        }
        catch (Exception e) {
            imageTasks.Remove(imageTask);
            Debug.Log("Download failed\n" + e);
        }
    }
}

Have I created a race condition that I'm not seeing?
Or why would a caught TaskCanceledException stop the other Tasks from completing?

(It should be a recoverable exception, and a return null is acceptable.)

It may be worth noting that I don't believe the problem lies with the interleaving, calling function. The same trouble occurs if the calling function is structured like this:

Task<List<string>> dl_task = DownloadURLsAsync();

List<string> screenshotURLs = await dl_task;
foreach(string s in screenshotURLs ) {
    await DownloadScreenshotAsync(s);
}
share|improve this question
  • If this is a Unity related issue, you should tag it accordingly. – Paulo Morgado Apr 16 at 6:18
  • I didn't use the Unity tag because it didn't seem to be a Unity-specific question. Tags used seemed most relevant, and it's capped at 5 tags. Is there an element of the question that is Unity-dependent? – Jimmy Alger Apr 16 at 19:09

active oldest votes

Your Answer

StackExchange.ifUsing("editor", function () { StackExchange.using("externalEditor", function () { StackExchange.using("snippets", function () { StackExchange.snippets.init(); }); }); }, "code-snippets"); StackExchange.ready(function() { var channelOptions = { tags: "".split(" "), id: "1" }; initTagRenderer("".split(" "), "".split(" "), channelOptions); StackExchange.using("externalEditor", function() { // Have to fire editor after snippets, if snippets enabled if (StackExchange.settings.snippets.snippetsEnabled) { StackExchange.using("snippets", function() { createEditor(); }); } else { createEditor(); } }); function createEditor() { StackExchange.prepareEditor({ heartbeatType: 'answer', convertImagesToLinks: true, noModals: false, showLowRepImageUploadWarning: true, reputationToPostImages: 10, bindNavPrevention: true, postfix: "", onDemand: true, discardSelector: ".discard-answer" ,immediatelyShowMarkdownHelp:true }); } });
 
StackExchange.ready( function () { StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f49847625%2ftaskcanceledexception-thread-blocking%23new-answer', 'question_page'); } );

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged c# firebase asynchronous async-await race-condition or ask your own question.

StackExchange.ready(function(){$.get('/posts/49847625/ivc/5671');});
StackExchange.ready(function () { StackExchange.responsiveness.addSwitcher(); }) (function(i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function() { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m); })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga'); StackExchange.ready(function () { StackExchange.ga.init({ sendTitles: true, tracker: window.ga, trackingCodes: [ 'UA-108242619-1' ] }); StackExchange.ga.setDimension('dimension2', '|c#|firebase|asynchronous|async-await|race-condition|'); StackExchange.ga.setDimension('dimension3', 'Questions/Show'); StackExchange.ga.trackPageView(); }); /**/ var _qevents = _qevents || [], _comscore = _comscore || []; (function() { var ssl = 'https:' == document.location.protocol, s = document.getElementsByTagName('script')[0], qc = document.createElement('script'); qc.async = true; qc.src = (ssl ? 'https://secure' : 'http://edge') + '.quantserve.com/quant.js'; s.parentNode.insertBefore(qc, s); _qevents.push({ qacct: "p-c1rF4kxgLUzNc" }); /**/ var sc = document.createElement('script'); sc.async = true; sc.src = (ssl ? 'https://sb' : 'http://b') + '.scorecardresearch.com/beacon.js'; s.parentNode.insertBefore(sc, s); _comscore.push({ c1: "2", c2: "17440561" }); })();
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.432205 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO