回调应该在不同的线程上调用吗? 使用此代码:
client.ExecuteAsync<List<IngredientDto>>(request, Response =>
{
textBox1.Text += Response.Data.Count;
});
我收到“InvalidOperationException”:
"The calling thread cannot access this object because a different thread owns it."
回调不应该在 UI 线程上吗?还是我错了?
最佳答案
实际上,如果你查看源代码,你就会发现
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
关于multithreading - 不同线程上的响应回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10580013/