gpt4 book ai didi

c# - 任务不返回 IsCompleted 状态

转载 作者:太空宇宙 更新时间:2023-11-03 23:15:29 24 4
gpt4 key购买 nike

以下代码有一个错误:result 不包含任何状态; IsCompletedIsCanceledIsFaulted 总是错误的,但是我测试了Task 可以正常工作,哪里有问题?

var result = _dataService.SyncPoll(webApiPoll); 

if (result.IsCompleted)
{
_logger.Info("Execute sync, poll was completed");
poll.IsSynchronized = true;
poll.ServerStatus = ServerStatus.Active;
ctx.SaveChanges();
}

//////

public Task SyncPoll(PollDto poll)
{
if (!_isAuthorized)
{
return null;
}
var client = new ApiClient(_baseApiUrl, _authToken);
Task result = Task.Run(async () => await client.SyncPollWeb(poll));
return result;
}

///////

public async Task<HttpResponseMessage> SyncPollWeb(PollDto poll)
{
HttpResponseMessage resp;
//System.Diagnostics.Debugger.Launch();
using (var client = GetClient())
{
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(_authType, _accessToken);
resp = await client.PostAsJsonAsync<PollDto>("api/poll", poll);
}
return resp;
}

最佳答案

你实际上做的是fire and forget 所以你不具备这样的原则

问题来自await你必须添加 await 才能恢复状态

  var result =  await _dataService.SyncPoll(webApiPoll); 

//这里

 Task result = await   client.SyncPollWeb(poll);

关于c# - 任务不返回 IsCompleted 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37385798/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com