2011-11-16 55 views
4

編輯阿賈克斯後回導致所有其他網頁請求掛起,直到方法請求完成

確定這就是典型的,我想出一個可行的解決方案就在我尋求幫助的問題!

我的代碼現在使用線程來產生一個新的線程來獨立於當前請求執行索引。它似乎在工作。

,我想出了代碼:

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"; 
} 

任何人有什麼想法?

+0

是Document.Index做一些需要它被鎖定除了你存儲在一個靜態變量的文件?相反,將Document實例直接傳遞給IndexThisPage方法可能會更好。 – rossisdead

+0

是的,它使用keyoti的內部索引引擎來打開索引目錄並修改一些平面文件。 – Rollcredit

回答

2

你的答案是完全正確的。 如果您使用.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(); 
    } 
} 

感謝

+1

不幸的是我被困在.NET 3.5上 – Rollcredit