是否应该在不同的线程上调用回调? 使用此代码:
client.ExecuteAsync<List<IngredientDto>>(request, Response =>
{
textBox1.Text += Response.Data.Count;
});
我收到“InvalidOperationException”:
“调用线程无法访问此对象,因为另一个线程拥有它。”
回调不应该在UI线程上,或者我错了吗?
答案 0 :(得分:2)
实际上,如果你看一下源代码,你会看到
public virtual RestRequestAsyncHandle ExecuteAsync<T>(IRestRequest request, Action<IRestResponse<T>, RestRequestAsyncHandle> callback)
{
return ExecuteAsync(request, (response, asyncHandle) =>
{
IRestResponse<T> restResponse = response as RestResponse<T>;
if (response.ResponseStatus != ResponseStatus.Aborted)
{
restResponse = Deserialize<T>(request, response);
}
callback(restResponse, asyncHandle);//<--- this means that response & callback are executed at **same** thread.
});
}
这会导致:
您无法从非ui线程更新ui对象。如果是WPF,您可以使用Dispatcher
client.ExecuteAsync<List<IngredientDto>>(request, Response =>
{
Dispatcher.Invoke((Action)() => {textBox1.Text += Response.Data.Count;});
});
一般情况下,请参阅syncronization context