任务未从另一个任务运行

问题描述 投票:0回答:1

在.Net 4.5中 此方法将任务添加到列表中。

//This method returns Datetime.
var task = Task.Factory.StartNew(() => ProcessPost(_blockSize), token);
tasks.Add(task);

我想运行另一个进程,但 ReturnString 方法出现错误。

public virtual DateTime ProcessPost(int blockSize)
{
    Interlocked.Add(ref totalToProcess, blockSize);
    DateTime finishTask;
    try
    {
        for (int i = 0; i < blockSize; i++)
        {
            try
            {
                bool isSuccess = stackProcesos.TryPop(out documento);
                if (isSuccess)
                {
                    // Verifies if document exist.
                    if (!HelperString.IsNullOrEmpty(documento.ruta) && HelperFile.ExistsFile(documento.ruta)){}
                    else
                    {
                    //In this part ocurrs an error.
                        if (!HelperString.IsNullOrEmpty(documento.number))
                        {
                            ConsultorSTR consultor = new ConsultorSTR();
                            var baseTask = consultor.ReturnString(documento.number, documento.token);
                                    
                            //no execution I don't know why
                            baseTask.Wait();
                                    
                            //other things
                        }
                    };

                }
            }
            catch (Exception ex)
            {}
        }
    }
    catch (Exception e)
    {}
}

ReturnString 执行 PostAsync,但该过程永远不会开始也永远不会结束。

 public async Task<string> ReturnString(string Number, string token)
 {
         var XmlRequestContent = new StringContent($"foo-content", Encoding.UTF8, "text/xml");
         
         //Response never comes
         var response = await client.PostAsync("url/api/returnData", XmlRequestContent);
         return "";
 }

ReturnString 在另一个项目中有效,但在这个项目中无效,有什么解决方案吗?

c# asp.net api task .net-4.5
1个回答
0
投票

您的代码可能陷入僵局,因为您正在执行异步同步。相反,使用

await

使此代码完全异步

您还应该删除空的

catch
块,以便正确传播错误,并且无论您是否设法
totalToProcess
,您都会在递增
Pop
时出现逻辑错误。

public virtual async Task<DateTime> ProcessPost(int blockSize)
{
    for (int i = 0; i < blockSize; i++)
    {
        bool isSuccess = stackProcesos.TryPop(out documento);
        if (!isSuccess)
            break;

        Interlocked.Increment(ref totalToProcess);
        // Verifies if document exist.
        if (!HelperString.IsNullOrEmpty(documento.ruta) && HelperFile.ExistsFile(documento.ruta))
            continue;

        if (!HelperString.IsNullOrEmpty(documento.number))
        {
            ConsultorSTR consultor = new ConsultorSTR();
            await consultor.ReturnString(documento.number, documento.token);
                                    
                //other things
        }
    }
    return someValueHere;
}
© www.soinside.com 2019 - 2024. All rights reserved.