提问人:Allan 提问时间:8/29/2023 最后编辑:Brian Tompsett - 汤莱恩Allan 更新时间:8/31/2023 访问量:72
任务未从其他任务运行
Task not running from another task
问:
在 .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
在另一个项目中工作,但不在这个项目中,有什么解决方案吗?
答:
0赞
Charlieface
8/30/2023
#1
您的代码可能处于死锁状态,因为您正在执行异步同步。相反,使用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;
}
评论
await
var baseTask = consultor.ReturnString(documento.number, documento.token);