Change request's behavior #1812
-
|
Is there a way to change the 'every request behavior' of a Refit Service? What I want is to do some cleanup on my app's main thread. I want the request to be made in a different thread, something like:
I'm not doing it on every request because will be headache and pretty hard to maintain. Any suggestions? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
Refit returns a Task, so the actual HTTP call already runs off the calling thread - awaiting it does not block your main thread while the request is in flight. You generally do not need Task.Run for that. A few options depending on what you actually want:
services
.AddRefitClient<IMyApi>()
.ConfigureHttpClient(c => c.BaseAddress = new Uri("https://api.example.com"))
.AddHttpMessageHandler(() => new MyHandler());A DelegatingHandler is the maintainable place for cross-cutting per-request behavior. |
Beta Was this translation helpful? Give feedback.
Refit returns a Task, so the actual HTTP call already runs off the calling thread - awaiting it does not block your main thread while the request is in flight. You generally do not need Task.Run for that.
A few options depending on what you actually want:
If you just want to free the UI/main thread while the call happens: await the Refit method directly. The continuation resumes on the captured context. If you do not need the captured context for post-processing, add ConfigureAwait(false) at the call site.
If you want all continuations to stay off the UI thread for an entire call chain, wrap the top-level call once: await Task.Run(() => api.HttpGet()). You do not need this per request.