2011-07-26 142 views
0

如何從線程向web服務發出異步請求?異步請求到Web服務

+0

爲了迴應您的第一點,如果您使用啓用Silverlight的WCF服務,silverlight會自動爲您生成異步代碼,例如,服務上的GetData()方法將在客戶端生成GetDataCompleted和GetDataAsync方法供您使用。 – Midimatt

+0

是的,但我需要在單獨的線程上執行此操作,以防止用戶嘗試在UI中執行其他操作時掛起UI。 – Joan

+0

所有的代碼都運行在__a__線程中,但我懷疑你的意思是你不想在UI線程不正確的線程中發出異步請求? – AnthonyWJones

回答

0

這是一個使用WCF的解決方案。

服務代碼FileService.svc

public class FileService 
{ 
    [OperationContract] 
    public byte[] GetFile(string filename) 
    { 
     byte[] File; 
     //do logic 

     return File; 
    } 
} 

客戶端代碼

public int requested_file_count = 5; 
public list<string> filenames; 

public FileServiceClient svc 

//Constructor 
public Example() 
{ 
    svc = new FileServiceClient(); 
} 

Public void GetFiles() 
{ 
    //Initialise the list of names and set the count of files received  
    filenames = new list<string>(5); 
    requested_file_count = filenames.Count; 

    svc.GetFileCompleted += new EventHandler<GetFileCompletedEventArgs>(GetFile_Completed); 

    //Call the Async Method passing it the file name and setting the userstate to 1; 

    svc.GetFileAsync(filenames[0],1); 
} 

void GetFile_Completed(object Sender, GetFileCompletedEventArgs e) 
{ 
    if (e.UserState == requested_file_count) 
    { 
    //All files have been downloaded 
    } 
    else 
    { 
     svc.GetFileAsync(filenames[e.UserState],++e.UserState); 
    } 

    //Do Something with the downloaded file 
    byte[] filedata = e.result; 
} 
+0

我正在做這樣的事情。但我需要在單獨的線程上完成它 – Joan

+0

對web服務和更新數據結構的異步請求應該發生在單獨的線程中。任何想法如何去做。 – Joan

+0

據我所知,服務調用正在單獨的線程中運行。 – Midimatt

1

這裏是沒有解釋的負載簡短的回答。

之前調用Async方法您的客戶對象上,確保您不會在UI線程上運行: -

System.Threading.ThreadPool.QueueUserWorkItem(o => 
{ 
    try 
    { 
     svc.SomeMethodAsync(); 
    } 
    catch (err) 
    { 
     // do something sensible with err 
    } 
}); 

現在相應的完成事件發生在ThreadPool線程沒有UI線程。