gpt4 book ai didi

c# - Ajax 回发导致所有其他 Web 请求挂起,直到方法请求完成

转载 作者:行者123 更新时间:2023-11-30 12:33:55 25 4
gpt4 key购买 nike

编辑

好吧,这很典型,我在寻求帮助后就想出了一个可能的解决方案!

我的代码现在使用 Threading 生成一个新线程来独立于当前请求执行索引。它似乎在起作用。

我想出的代码:

private static WebDocument Document;
private static readonly object Locker = new object();

[WebMethod(true)]
public static string Index(string uri)
{
WebDocument document = WebDocument.Get(uri);

if (document == null)
document = WebDocument.Create(uri);

Document = document;
Thread thread = new Thread(IndexThisPage);
thread.Start();

//document.Index();

return "OK";
}

public static void IndexThisPage()
{
lock (Locker)
{
Document.Index();
}
}

原始问题

在我的所有页面上,我都有一个 ajax 帖子,它在当前页面以及页面上的所有文档上执行索引。我使用的索引器是 Keyoti。

似乎发生的情况是,当一个页面被索引时,对任何其他页面的任何请求似乎都没有响应(即它停留在“等待服务器”),直到索引完成。注意:我从同一台机器加载不同的页面,因为代码是本地的。

这是我正在使用的 ajax:

<script type="text/javascript" src="/Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
$(window).load(function () {
$.ajax({
type: "POST",
url: "/DoIndex.aspx/Index",
data: "{ uri: '" + self.location + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
</script>

及其调用的方法:

[WebMethod(true)]
public static string Index(string uri)
{
WebDocument document = WebDocument.Get(uri);

if (document == null)
document = WebDocument.Create(uri);

document.Index();

return "OK";
}

有人有什么想法吗?

最佳答案

你的回答完全正确。如果您使用 .Net 4,我想让您知道您可以使用任务而不是线程。我想它更容易阅读,而且它会让操作系统决定如何管理线程。

this is the good explanation as well.

private static WebDocument Document;
private static readonly object Locker = new object();

[WebMethod(true)]
public static string Index(string uri)
{
WebDocument document = WebDocument.Get(uri);

if (document == null)
document = WebDocument.Create(uri);

Document = document;

// start a new background thread
var System.Threading.Tasks.task = Task.Factory.StartNew(() => IndexThisPage);

//document.Index();

return "OK";
}

public static void IndexThisPage()
{
lock (Locker)
{
Document.Index();
}
}

谢谢

关于c# - Ajax 回发导致所有其他 Web 请求挂起,直到方法请求完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8160414/

25 4 0