question

Subazzz-3626 avatar image
0 Votes"
Subazzz-3626 asked ·

Data reader LoadAsync() throws "System.InvalidOperationException: A method was called at an unexpected time"

I have created two UWP apps to share files from server app to client app using Stream Sockets. In server app, it will add new data to the database and create StreamSocketListener to listen incoming connection to a button click. In client app, it is polling for new data in database and if there is a new data it will read data using Data reader.

Client code

 public ClientScreen()
         {
             this.InitializeComponent();
            Loaded += async (o, e) =>
            {
                await Task.Run(() => PollProcess());
            };
         }
 
 private async Task PollProcess()
         {
             //Polling task values
             int delay = 20000;
             while (true)
             {               
                 // web service call to check new record in database
                 await GetDatabaseData();
                 await Task.Delay(delay);
             }
         }
 
 // Inside success of web service call
 private async Task ExtractFileData()
         {
             DataReader reader;
             byte[] byteArray;
 
             try
             {
                 using (reader = new DataReader(App.clientSocket.InputStream))
                 { 
                     //Read first 4 bytes(length of the subsequent string).
                     var timeoutSource = new CancellationTokenSource(50000);
                     uint sizeFieldCount = await reader.LoadAsync(sizeof(uint)).AsTask(timeoutSource.Token);
                    
                     if (sizeFieldCount != sizeof(uint))
                     {
                         return;
                     }
 
                     // Read the file length.
                     uint fileLength = reader.ReadUInt32();
                     // Read the bytes.
                     var timeoutSource1 = new CancellationTokenSource(50000);
                     uint actualFileLength = await reader.LoadAsync(fileLength).AsTask(timeoutSource1.Token);                  
                     if (fileLength != actualFileLength)
                     {                   
                        return;
                     }
                     byteArray = new byte[actualFileLength];
                     reader.ReadBytes(byteArray);
                     if (App.type == "Image")
                     {
                         await ImageLoadAsync(byteArray);
                     }
                    
                 }
             }
             catch (Exception e)
             {
                    // Print exception message
             }
         }


Here, it throws "System.InvalidOperationException: A method was called at an unexpected time" exception in most of the time. When I put debug pointers, it executes the flow in order. It seems await LoadAsync() does not wait even though it is an async method.

Any idea on this is much appreciated.

uwp
· 2
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

I checked your code, unfortunately, we could not create a code sample with above, the better way is that provide us min complete sample with oneDrive of github .

0 Votes 0 · ·

Could you provide the caller for ExtractFileData() method?

1 Vote 1 · ·

1 Answer

Subazzz-3626 avatar image
0 Votes"
Subazzz-3626 answered ·

@yanxiaodi, This is the caller method.

     private async void GetDatabaseData()
             {
                 AppUtils.PrintDebug("==========Start", CLASS_NAME, "GetSharedMobileResource");
                 if (AppUtils.HasInternet())
                 {
                     AppUtils.PrintDebug("==========Has Internet ", CLASS_NAME, "GetSharedMobileResource");
                     await restWSClient.GetMobileResource(classroomId).ContinueWith(async responseMsg =>
                     {
                         AppUtils.PrintDebug("==========GetSharedMobileResource Response : " + responseMsg.Result, CLASS_NAME, "GetSharedMobileResource()");
     
                         if (responseMsg != null && responseMsg.Result != null && !responseMsg.IsFaulted)
                         {
                             var responseContent = responseMsg.Result.Content.ReadAsStringAsync();
                             if (responseMsg.Result.StatusCode == HttpStatusCode.OK)
                             {
                                 AppUtils.PrintDebug("=========OK ", CLASS_NAME, "GetSharedMobileResource()");
                                 if (responseContent != null && responseContent.Result != null && !responseContent.IsFaulted)
                                 {
                                     AppUtils.PrintDebug("=========content : " + responseContent.Result, CLASS_NAME, "GetSharedMobileResource()");
                                     string json = responseContent.Result;
                                     JObject joResponse = JObject.Parse(responseContent.Result);
                                     JArray payloadArray = (JArray)joResponse["payload"];
     
                                     AppUtils.PrintDebug("=========payloadArray : " + payloadArray, CLASS_NAME, "GetSharedMobileResource()");
                                     if (payloadArray != null)
                                     {
                                         string serverIP = "";
                                         foreach (JObject resource in payloadArray)
                                         {
                                             if (resource != null)
                                             {
                                                 string jsonResource = resource.ToString();
                                                 serverIP = (string)JObject.Parse(jsonResource)["IWIP"];
                                                 App.fileType = (string)JObject.Parse(jsonResource)["ResourceType"];
                                                 string path = (string)JObject.Parse(jsonResource)["ResourcePath"];
                                                 App.fileName = Path.GetFileName(path);
                                                 prevSharedFileId = sharedFileId;
                                                 sharedFileId = (string)JObject.Parse(jsonResource)["Id"];
                                             }
                                         }                            
                                         if (sharedFileId != "" && prevSharedFileId != sharedFileId)
                                         {                                        
                                             StudentShareClient shareClient = new StudentShareClient(serverIP);
                                             if (App.fileType == "Image" || App.fileType == "Video")
                                             {                                
                                                 await ExtractFileData();
                                             }
                                         }
                                     }
                                     else
                                     {
                                         //payload null
                                         AppUtils.PrintDebug("=========payload is null ", CLASS_NAME, "GetSharedMobileResource()");
                                         await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                                         {
                                             await AppUtils.ShowMessage(Constants.ERROR_CONTACT_ADMIN);
                                         });
                                     }
                                 }
                                 else
                                 {
                                     //content null
                                     AppUtils.PrintDebug("=========content is null ", CLASS_NAME, "GetSharedMobileResource()");
                                     await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                                     {
                                         await AppUtils.ShowMessage(Constants.ERROR_CONTACT_ADMIN);
                                     });
                                 }
                             }
                             else if (responseMsg.Result.StatusCode == Constants.HTTP440)
                             {
                                 // Redirect to Login
                                 Frame rootFrame = Window.Current.Content as Frame;
                                 rootFrame.Navigate(typeof(LoginScreen), null, new SuppressNavigationTransitionInfo());
     
                             }
                             else if (responseMsg.Result.StatusCode == HttpStatusCode.InternalServerError)
                             {
                                 //Internal Server Error
                                 AppUtils.PrintDebug("=========InternalServerError ", CLASS_NAME, "GetSharedMobileResource()");
                                 if (responseContent != null && responseContent.Result != null && !responseContent.IsFaulted)
                                 {
                                     AppUtils.PrintDebug("=========content : " + responseContent.Result, CLASS_NAME, "GetSharedMobileResource()");
     
                                     try
                                     {
                                         JObject joResponse = JObject.Parse(responseContent.Result);
                                         JObject statusMsg = (JObject)joResponse["status"];
     
                                         AppUtils.PrintDebug("=========status : " + statusMsg, CLASS_NAME, "GetSharedMobileResource()");
                                         if (statusMsg != null)
                                         {
                                             string msgDesc = (string)statusMsg["message"];
                                             await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                                             {
                                                 await AppUtils.ShowMessage(msgDesc);
                                             });
                                         }
                                         else
                                         {
                                             await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                                             {
                                                 await AppUtils.ShowMessage(Constants.ERROR_INTERNAL);
                                             });
                                         }
                                     }
                                     catch (Exception e)
                                     {
                                         await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                                         {
                                             await AppUtils.ShowMessage(Constants.ERROR_CONTACT_ADMIN);
                                         });
                                     }
     
                                 }
                                 else
                                 {
                                     //content null
                                     await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                                     {
                                         await AppUtils.ShowMessage(Constants.ERROR_CONTACT_ADMIN);
                                     });
                                 }
                             }
                             else
                             {
                                 //Unexpected error
                                 AppUtils.PrintDebug("=========Other error ", CLASS_NAME, "GetSharedMobileResource()");
                                 if (responseContent != null && responseContent.Result != null && !responseContent.IsFaulted)
                                 {
                                     AppUtils.PrintDebug("=========content : " + responseContent.Result, CLASS_NAME, "GetSharedMobileResource()");
                                     try
                                     {
                                         JObject joResponse = JObject.Parse(responseContent.Result);
                                         JObject statusMsg = (JObject)joResponse["status"];
     
                                         AppUtils.PrintDebug("=========status : " + statusMsg, CLASS_NAME, "GetSharedMobileResource()");
                                         if (statusMsg != null)
                                         {
                                             string msgDesc = (string)statusMsg["message"];
                                             await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                                             {
                                                 await AppUtils.ShowMessage(msgDesc);
                                             });
     
                                         }
                                         else
                                         {
                                             await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                                             {
                                                 await AppUtils.ShowMessage(Constants.ERROR_CONTACT_ADMIN);
                                             });
                                         }
                                     }
                                     catch (Exception e)
                                     {
                                         await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                                         {
                                             await AppUtils.ShowMessage(Constants.ERROR_CONTACT_ADMIN);
                                         });
                                     }
     
                                 }
                                 else
                                 {
                                     //content null
                                     await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                                     {
                                         await AppUtils.ShowMessage(Constants.ERROR_CONTACT_ADMIN);
                                     });
                                 }
                             }
                         }
                         else
                         {
                             //responseMsg or responseMsg.Result is null
                             AppUtils.PrintDebug("=========responseMsg or responseMsg.Result is null ", CLASS_NAME, "GetSharedMobileResource()");
                             await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                             {
                                 await AppUtils.ShowMessage(Constants.ERROR_CONTACT_ADMIN);
                             });
                         }
     
                     });
                     AppUtils.PrintDebug("==========End", CLASS_NAME, "GetSharedMobileResource");
                 }
                 else
                 {
                     AppUtils.PrintDebug("==========No internet", CLASS_NAME, "GetSharedMobileResource");
                     await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                     {
                         await AppUtils.ShowMessage(Constants.ERROR_NO_INTERNET_ACCESS);
                     });
                 }
             }
 


· 2 · Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Instances of DataReader objects do not support concurrent read operations. Could you please check if you have concurrent reading in the method?

Also, I don't think you should wait for PollProcess() method because it is an infinite loop. You could just start it and forget it by removing the await keyword.

0 Votes 0 · ·

When I changed poll method it seems worked. But it needed at least 1 min timeout. But we cannot have that much timeout.

 public ClientScreen()
         {
             this.InitializeComponent();          
             ThreadPoolTimer timer = ThreadPoolTimer.CreatePeriodicTimer((t) =>
             {
                GetDatabaseData();
             }, TimeSpan.FromSeconds(50));
         }

0 Votes 0 · ·