防止竞争条件
我正在使用 MVC2 的内置 ajax 功能。基本上,用户键入搜索查询,然后按每个键都会显示一组查询结果。这在几乎所有情况下都可以正常工作,但有时服务器在单个响应时有点慢,因此下一个击键的结果会在上一个击键之前返回。当先前的击键结果集最终返回给客户端时,它将覆盖实际上应该显示的较新搜索查询的结果。
我的代码或多或少遵循以下原则:
<% using (Ajax.BeginForm("SearchUser", null,
new AjaxOptions()
{ UpdateTargetId = "findUserResults" },
new { id = "findUserAjaxForm" })) {%>
每次击键都会提交此表单,从而在“findUserResults”元素中输出结果。
如何防止显示较旧的结果,同时仍然使用 MVC2 中提供的内置函数?
I'm using the built-in ajax functionality of MVC2. Basically the user types a search query, and on every key press a set of results for the query is shown. This works fine in almost all cases, but sometimes the server is a bit slow with a single response, and thus the result for the next key stroke is returned before the previous. When the previous key stroke result set is finally returned to the client it will overwrite the results for the newer search query that should actually have been shown.
My code follows more or less along these lines:
<% using (Ajax.BeginForm("SearchUser", null,
new AjaxOptions()
{ UpdateTargetId = "findUserResults" },
new { id = "findUserAjaxForm" })) {%>
Every keystroke submits this form and thus outputs the results in the 'findUserResults' element.
How can I prevent older results from being displayed while still making use of the built-in functions provided in MVC2?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在每个请求中发送一个时间戳,并将其与结果一起返回,然后仅在时间戳晚于前一个请求时才显示结果。
返回自纪元开始以来的毫秒数。
或者,您可以在每个页面上使用递增计数器。
You could send a timestamp with each request and return it with the result, then only show the result if the timestamp is after the the previous one.
returns milliseconds since the start of the epoch.
Alternatively you could just use an incrementing counter on each page.