异步模块或处理程序在异步操作仍挂起时完成

本文关键字:挂起 异步操作 模块 处理 程序 异步 | 更新日期: 2023-09-27 18:09:24

我正在研究机器人技术,在我的一个项目中,我写了以下几行代码

private async void DeliveryProgressReport(IDialogContext context, Activity message)
    {
        MessagesController.progressdetails = SQLDatabaseService.getinprogressdetails();
        var progress = MessagesController.progressdetails;
        if (progress.Count > 0)
        {
            try
            {
                Activity replyToConversation = message.CreateReply("**In Progress Report Details**");
                replyToConversation.Recipient = message.From;
                replyToConversation.Type = "message";
                replyToConversation.Attachments = new List<Attachment>();
                Dictionary<string, string> progresslist = new Dictionary<string, string>();
                foreach (var progressreport in progress)
                {
                    //Invoke the machine learning model for predicting the delivery status of delivery person
                    //var deliveryStatus= await InvokeRequestResponseServiceOfDeliveryPersonPredictionExp1();
                    //await Task.Delay(TimeSpan.FromSeconds(5));
                    var deliveryStatus = await InvokeRequestResponseServiceOfDeliveryPersonPredictionExp(progress[0].Name, progress[0].Mobile_Number);
                    progresslist.Add(progressreport.Name, progressreport.Mobile_Number);
                    List<CardImage> cardImages = new List<CardImage>();
                    cardImages.Add(new CardImage(url: progressreport.Photo_Url));
                    ThumbnailCard tlcard = new ThumbnailCard()
                    {
                        Title = "Name:" + progressreport.Name,
                        Subtitle = "Call:" + progressreport.Mobile_Number,
                        Images = cardImages,
                        Text = "Staus by Using Machine Learning Prediction:" + deliveryStatus
                    };
                    Attachment plAttachment = tlcard.ToAttachment();
                    replyToConversation.Attachments.Add(plAttachment);
                }
                replyToConversation.AttachmentLayout = AttachmentLayoutTypes.List;
                await context.PostAsync(replyToConversation);
            } catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
        else
        {
            Activity replyToConversation = message.CreateReply("**There are no in progress deliveries are found**");
            await context.PostAsync(replyToConversation);
        }
    }
    private async Task<string> InvokeRequestResponseServiceOfDeliveryPersonPredictionExp(string name, string mobile_Number)
    {
         string status = "";
        //Func<Stream, Task> copyStreamAsync = async stream =>
        //{
        //await Task.Factory.StartNew(async () =>
        //{
        //using (stream)
        //using (var sourceStream = await sourceContent.Content.ReadAsStreamAsync())
        //{
        //    await sourceStream.CopyToAsync(stream);
        //}
        //var client = new HttpClient();
        using (var client = new HttpClient())
        {
            var scoreRequest = new
            {
                Inputs = new Dictionary<string, StringTable>() {
            {
                "input1",
                new StringTable()
                {
                    ColumnNames = new string[] {"Id", "Name", "Mobile_Number", "CourierCompany_Name", "Status", "EmailId"},
                    Values = new string[,] {  { "", name, mobile_Number, "", "","" }, { "", name, mobile_Number, "", "", "" }, }
                }
            },
        },
                GlobalParameters = new Dictionary<string, string>()
                {
                }
            };
            const string apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx=="; // Replace this with the API key for the web service
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
            client.BaseAddress = new Uri("My Request URL");
            // WARNING: The 'await' statement below can result in a deadlock if you are calling this code from the UI thread of an ASP.Net application.
            // One way to address this would be to call ConfigureAwait(false) so that the execution does not attempt to resume on the original context.
            // For instance, replace code such as:
            //      result = await DoSomeTask()
            // with the following:
            //      result = await DoSomeTask().ConfigureAwait(false)
            //var status = await PostRequest(scoreRequest,client).ConfigureAwait(false);
            HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest);//.ConfigureAwait(false);
            string correctLocation = "";
            string wrongLocation = "";
            string notReached = "";
            string personMismatch = "";
            if (response.IsSuccessStatusCode)
            {
                string result = await response.Content.ReadAsStringAsync();
                var results = JsonConvert.DeserializeObject<RootObject>(result);
                foreach (var value in results.Results.output1.value.Values)
                {
                    status = value[8].ToString();
                    correctLocation = value[4].ToString();
                    notReached = value[5].ToString();
                    personMismatch = value[6].ToString();
                    wrongLocation = value[7].ToString();
                }

                Debug.WriteLine("Result: {0}", result);
                return status;
            }
            else
            {
                Debug.WriteLine(string.Format("The request failed with status code: {0}", response.StatusCode));
                // Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
                Debug.WriteLine(response.Headers.ToString());
                string responseContent = await response.Content.ReadAsStringAsync();
                Debug.WriteLine(responseContent);
                return status;
            }
        };
        // return status;
    }

在执行下面一行之后,我得到了异常,如异步模块或处理程序完成,而异步操作仍在等待

等待context.PostAsync (replyToConversation);

在发布这个问题之前,我已经通过下面的链接,但我没有解决它。

Async Void;Net和未完成操作数

Web Api + HttpClient:异步模块或处理程序在异步操作尚未完成时完成

请告诉如何解决这个异常。

pradeep

异步模块或处理程序在异步操作仍挂起时完成

最后,当我在DeliveryProgressReport方法中返回Task而不是void时,我解决了上述异常。而且每当我调用await DeliveryProgressReport()方法时,我也会返回Task而不是void

pradeep