I work on a document downloader in a windows store app, and I have a problem with tasks. So here is a sample of my code :
Task created and started
...
HttpDownloader httpDownloader = new HttpDownloader(server);
Action<object> action = (object doc ) => httpDownloader.DownloadDocument((Document)doc);
Task t1 = new Task(action,selection.doc);
t1.Start();
...
DownloadDocument method
...
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
// Dropdown of file types the user can save the file as
savePicker.FileTypeChoices.Add("Application/pdf", new List<string>() { ".pdf" });
// Default file name if the user does not type one in or select a file to replace
savePicker.SuggestedFileName = doc.name+"_"+doc.version;
StorageFile file = await savePicker.PickSaveFileAsync(); // Here an exception is launch.
...
And every time I get :
Element not found (Exception de HRESULT : 0x80070490)
Without task, my code works fine, but since I want to use tasks to manage the different download, I have this error.
Your Action
runs on a random pool thread, which is different from your main thread (as scheduled by Task.Start
). There you access your doc
object which, I assume, was created on the main thread. This might be the reason for the fault.
Generally, you should not access objects (especially UI elements) across differed threads, unless they are specifically designed to be thread-safe.
EDITED: You probably do not need a task here. Just do await savePicker.PickSaveFileAsync()
and mark your outer method as async
(the method which currently creates the task).
To understand better what thread you're on, it may help to add a debug trace like this:
Debug.Print("<Method name>, Thread: {0}", Thread.CurrentThread.ManagedThreadId);
User contributions licensed under CC BY-SA 3.0