[英]Why instead of two different AsyncTasks one executes two times?
So I have code where I send request to the server and get the response. 所以我有代码,我发送请求到服务器并获得响应。 Response depends on the set of parameters which I send to the server.But because of some reason I got the same result.Here is a code: I call
sendDashboardRequest
for two different set of parameters: 响应取决于我发送给服务器的参数集。但由于某种原因我得到了相同的结果。这是一个代码:我为两个不同的参数集调用
sendDashboardRequest
:
LinkedHashMap<String, Object> serverParameters = new LinkedHashMap<String, Object>();
serverParameters.put("user_id", result.get("user_id"));
serverParameters.put("limit", Integer.valueOf(1000).toString());
serverParameters.put("type", Integer.valueOf(1).toString());
sendDashboardRequest(serverParameters);
serverParameters.put("type", Integer.valueOf(2).toString());
sendDashboardRequest(serverParameters);//Executes only this AsyncTask twice!
And here is code of the method sendDashboardRequest
which starts new AsyncTasks: 这里是
sendDashboardRequest
方法的代码,它启动新的AsyncTasks:
public void sendDashboardRequest(LinkedHashMap<String, Object> params) {
new AsyncTask<LinkedHashMap<String, Object>, Void, LinkedHashMap<String, Object>>()
{
NetworkOp lowLevelOps = new NetworkOp();
@Override
protected LinkedHashMap<String, Object> doInBackground (LinkedHashMap<String, Object>... params)
{
return lowLevelOps.executeCommand(DASHBOARD_COMMAND, params[0]);
}
protected void onPostExecute(LinkedHashMap<String, Object> result)
{
//And here I gave the same result!But parameters which I send to the server are different!
}
}.execute(params);
}
The most interesting thing is when I create two different methods with same body and call each for the different set of parameters everything works well and two different AsyncTasks starts. 最有趣的是当我使用相同的主体创建两个不同的方法并且为不同的参数集调用每个方法时,一切运行良好并且两个不同的AsyncTasks开始。
You are sending the same LinkedHashMap
in both requests. 您在两个请求中发送相同的
LinkedHashMap
。 Since the requests are serviced in a background thread, the timing will be unpredictable and you can't guarantee that the background thread for the first request will execute before you issue the second request. 由于请求在后台线程中提供服务,因此时间将无法预测,并且您无法保证在发出第二个请求之前第一个请求的后台线程将执行。 In this case, by chance, the modified value in the second request is already in the map by the time the first request gets executed.
在这种情况下,偶然地,第二个请求中的修改值在执行第一个请求时已经在映射中。
You should use a different map for each request, or else change sendDashboardRequest
so that it copies the data it needs rather than relying on the passed-in map remaining constant. 您应该为每个请求使用不同的映射,或者更改
sendDashboardRequest
以便它复制所需的数据,而不是依赖传入的映射保持不变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.