我有一个包装 HttpClient 的“rest client”,它的方法是异步的。 除了其他原因,我需要控制我的其余客户端的登录/注销过程,以便不超过 session 数。
其余客户端实现 IDisposable 并且在处理客户端时,我需要检查客户端是否“仍处于登录状态”,如果是则退出。 由于在 Dispose 方法中进行任何类型的外部调用都被认为是不好的做法,因此我有如下内容
public class MappingsController : RestController
{
[HttpGet]
public async Task<HttpResponseMessage> GetYears()
{
return await ProcessRestCall(async rc => await rc.GetYearsAsync());
}
}
public class RestController : ApiController
{
protected async Task<HttpResponseMessage> ProcessRestCall<T>(Func<RestClient, Task<T>> restClientCallback)
{
RestClient restClient = null;
try
{
var credentials = GetCredentialsFromRequestHeader();
if (credentials == null)
{
return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Missing credentials from header!");
}
var username = credentials["Username"];
var password = credentials["Password"];
restClient = new RestClient(username, password);
var authenticated = await restClient.SignInAsync();
if (!authenticated)
{
return CreateErrorResponseWithRestStatus(HttpStatusCode.Unauthorized, restClient);
}
var result = await restClientCallback(restClient);
// Following works, but since I need to do it in finally block in case exception happens, perhaps It should be done in finally anyways...
//await restClient.SignOutAsync();
var response = Request.CreateResponse(HttpStatusCode.OK, result);
return response;
}
catch (Exception e)
{
return CreateErrorResponseWithRestStatus(HttpStatusCode.BadRequest, restClient, e);
}
finally
{
if (restClient != null)
{
if (restClient.IsSignedIn)
{
//var signedOutOk = restClient.SignOutAsync();//.Result; //<-- problem - this blocks!!!
restClient.SignOutAsync().ConfigureAwait(false); // seems to work, but I am not sure if this is kosher + I can't get return var
//Logger.Warn(CultureInfo.InvariantCulture, m => m("Client was still signed in! Attempt to to sign out was {0}", signedOutOk ? "successful" : "unsuccessful"));
}
restClient.Dispose();
}
}
}
}
请您参考如下方法:
.ConfigureAwait(false) 的使用不是问题。 你根本没有在等待任务。因为你没有await它,所以await被配置成什么并不重要做。
您所做的只是基本的即发即弃(您可能会接受也可能不会接受)。
无论如何,您都应该删除 ConfigureAwait(false),因为它什么都不做,而且会让读者感到困惑。如果您可以发送注销请求但实际上没有注销,那么这没问题。
如果您需要确保在注销请求返回之前不调用 restClient.Dispose();,那么您有点……问题。问题源于注销请求可能不成功,或者更糟糕的是,它可能根本没有响应。你需要一些方法来处理它。
您不能在 finally block 中使用 await,但您可以或多或少地通过延续来模仿它的行为。你可能需要做这样的事情:
public static async Task DoStuff()
{
IDisposable disposable = null;
try { }
finally
{
var task = GenerateTask();
var continuation = Task.WhenAny(task, Task.Delay(5000))
.ContinueWith(t =>
{
if (task.IsCompleted) //if false we timed out or it threw an exception
{
var result = task.Result;
//TODO use result
}
disposable.Dispose();
});
}
}
请注意,由于您没有使用 await,因此从 DoStuff 返回的任务将在第一次到达 finally block 时指示它已“完成”时间;不是在继续触发并且对象被处置时。这可能会或可能不会被接受。
