Rik*_*nin 5 c# xamarin.android refit
我在我的Xamarin App中使用Refit库,我想为请求设置10秒超时.有没有办法在改装中这样做?
接口:
interface IDevice
{
[Get("/app/device/{id}")]
Task<Device> GetDevice(string id, [Header("Authorization")] string authorization);
}
Run Code Online (Sandbox Code Playgroud)
调用API
var device = RestService.For<IDevice>("http://localhost");
var dev = await device.GetDevice("15e2a691-06df-4741-b26e-87e1eecc6bd7", "Bearer OAUTH_TOKEN");
Run Code Online (Sandbox Code Playgroud)
Ben*_*thy 15
接受的答案是为单个请求强制执行超时的正确方法,但如果要为所有请求设置单个一致的超时值,则可以传递预配置HttpClient及其Timeout属性集:
var api = RestService.For<IDevice>(new HttpClient
{
BaseAddress = new Uri("http://localhost"),
Timeout = TimeSpan.FromSeconds(10)
});
Run Code Online (Sandbox Code Playgroud)
这是一个示例项目.
Rik*_*nin 11
我终于找到了一种在Refit中为请求设置超时的方法.我用过CancelationToken.这是添加后修改后的代码CancelationToken
接口:
interface IDevice
{
[Get("/app/device/{id}")]
Task<Device> GetDevice(string id, [Header("Authorization")] string authorization, CancellationToken cancellationToken);
}
Run Code Online (Sandbox Code Playgroud)
调用API:
var device = RestService.For<IDevice>("http://localhost");
CancellationTokenSource tokenSource = new CancellationTokenSource();
tokenSource.CancelAfter(10000); // 10000 ms
CancellationToken token = tokenSource.Token;
var dev = await device.GetDevice("15e2a691-06df-4741-b26e-87e1eecc6bd7", "Bearer OAUTH_TOKEN", token);
Run Code Online (Sandbox Code Playgroud)
它适合我.我不知道这是不是正确的方式.如果是错的,请提出正确的方法.
| 归档时间: |
|
| 查看次数: |
3072 次 |
| 最近记录: |