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

Subazzz 1 Reputation point
2019-12-04T06:44:04.57+00:00

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.

Universal Windows Platform (UWP)
{count} votes

1 answer

Sort by: Most helpful
  1. Subazzz 1 Reputation point
    2019-12-04T09:08:09+00:00

    @Xiaodi Yan , 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);  
                        });  
                    }  
                }  
    
    
    
      
    

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.