1

The docs state to call all methods of FilePicker on the ui-thread, so I made the following call:

await MainThread.InvokeOnMainThreadAsync(async () =>
{
    IEnumerable<FileResult> images = await FilePicker.PickMultipleAsync(new PickOptions()
    {
        FileTypes = new FilePickerFileType(new Dictionary<DevicePlatform, IEnumerable<string>>
        {
            { DevicePlatform.WinUI, [".jpg", ".png", ".jpeg", ".bmp", ".tif", ".tiff"] }
        })
    });
    ... // some code to parse the images
});

The windows explorer opens and I can choose multiple images, but as soon as I click "open" or "cancel" PickMultipleAsync throws a System.Runtime.InteropServices.COMException with the message The application called an interface that was marshalled for a different thread. (0x8001010E (RPC_E_WRONG_THREAD)).

Anyone having any ideas?

Edit: What i've forgot to mention is that the problem only appears sometimes.

5
  • 3
    Is the COMException thrown on the FilePicker.PickMultipleAsync line exactly? Commented May 20 at 7:15
  • I would be careful with running code on the UI thread this way, since you do not know what the UI thread is doing at the moment. Could you provide some context about what you are doing and why you need a background thread to ask the UI thread for stuff? In most cases you want to provide background threads with everything they need up front. Commented May 20 at 11:36
  • @Twenty yes it is Commented May 30 at 8:47
  • @JonasH The exception is also being thrown without the MainThread.InvokeOnMainThreadAsync. Also in my case the code is running on the UI-thread anyway and not on a background thread. It's just one more layer of protection i've added, since the documentation states that it should be running on the ui-thread. Commented May 30 at 8:51
  • IMHO, code should either be explicitly designed for concurrency, or just single threaded, and it should be clear which is what. Throwing in InvokeOnMainThreadAsync "just to be safe" sounds like a poor practice to me. It results in more complicated code for no good reason, and could in worst case result in deadlocks. If it is designed to run on the UI thread it is better to trow an error if it is not, so you can fix the problem. Commented Jun 2 at 6:24

1 Answer 1

1

Typically, I use this.Dispatcher.Dispatch( async () => { } ), to schedule execution on the UI thread where this refers to an instance of a UI component, e.g. a ContentPage.

See also

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.