UWP (C#) program freezes after the path selector is displayed

XiaoLi8848 1 Reputation point
2021-07-11T02:27:53.573+00:00

I referenced Microsoft Learn and wrote a piece of C# code to make the program display a path selector, but VS showed an error message: await can only be used for asynchronous methods, refer to the use of async mark..., but this method is awaitable and has async mark. After trying to compile, there was an error message: "CompileXaml" task returned false, but no error was recorded.

After I changed it to ".AsTask().Result", the program can display the path picker, but the program freezes after it is displayed. Neither the main interface nor the path picker responds (but not the unresponsive state), please ask How to solve the problem?

   c#  
   var folderPicker = new Windows.Storage.Pickers.FolderPicker  
               {  
                   SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop  
               };  
               Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync(); ->ERROR  
               if (folder != null)  
               {  
                   pass  
               }  
               else  
               {  
                   pass  
               }  

113489-image.png

   c#  
   var folderPicker = new Windows.Storage.Pickers.FolderPicker  
               {  
                   SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop  
               };  
               Windows.Storage.StorageFolder folder = folderPicker.PickSingleFolderAsync().AsTask().Result;  
               if (folder != null)  
               {  
                   pass  
               }  
               else  
               {  
                   pass  
               }  
Developer technologies | Universal Windows Platform (UWP)
{count} votes

1 answer

Sort by: Most helpful
  1. AryaDing-MSFT 2,916 Reputation points
    2021-07-12T03:28:12.187+00:00

    Hi,

    Welcome to Microsoft Q&A!

    You need to include async keyword in the method declaration of any method in which you use the await operator. Please refer to the following code.

    public async void PickerFolder() {  
    …  
    StorageFolder folder = await folderPicker.PickSingleFolderAsync();   
    …  
    }    
    

    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.