我用 C# 创建了一个客户端 Web 服务,以便能够检索有关我从服务器获得的书籍的信息。
当我打电话从 bookId 获取我在 paremeter 中传递的书籍信息时,有时调用很快,有时需要 1 分钟,有时需要很长时间。我只将 bookId 存储在我的数据库中,所以当我需要有关书籍的更多信息(标题、出版日期等(时,我会联系网络服务以获取它们。我正在使用chrome调试器,在"网络"选项卡下,我只有"警告;请求尚未完成">...没有其他信息可以帮助我了解到底发生了什么!–
我调用的函数是getBooksByAuthor(authorId)
的,我应该只有 8 个与 authorId 相关的结果,所以它应该不会花那么长时间!这是我的所有代码:
public async Task<T> GetObject<T>(string uriActionString)
{
T wsObject =
default(T);
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(@"https://books.server.net");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// connect to the server
var byteArray = Encoding.ASCII.GetBytes("NXXXXX:Passxxxx");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
HttpResponseMessage response = await client.GetAsync(uriActionString);
response.EnsureSuccessStatusCode();
wsObject = JsonConvert.DeserializeObject<T>(await((HttpResponseMessage)response).Content.ReadAsStringAsync());
}
return wsObject;
}
catch (Exception e)
{
throw (e);
}
}
public async Task<Book> viewBook(int id)
{
Book book = new Book();
string urlAction = String.Format("api/book/{0}", id);
book = await GetWSObject<Book>(urlAction);
return book;
}
public string getBooksByAuthor (int authorId) {
string result = "";
var books = from a in db.Authors
where a.id == authorId
select new
{
id = a.id
};
foreach (var book in books.ToList())
{
var bookdata = await ws.viewBook(book .id);
result += this.getBookObject(book.id).name + ", ";
}
return result;
}
/* How to return a string from a task ? */
foreach (var author in listOfAuthors)
{
booksFromAuthors.Add(new { id = author.id, book = getBooksByAuthor(author.id) // ? how convert it to a string ? });
}
失去getBookObject函数,你只是通过在那里启动一个新任务使事情复杂化。
你可以简单地等待getBooksByAuthor的结果,如果你使该函数异步。
public async Task<Book> getBook(int id)
{
string urlAction = String.Format("api/book/{0}", id);
return await GetWSObject<Book>(urlAction);
}
public async Task<string> getBooksByAuthor (int authorId)
{
string result = "";
var books = from a in db.Authors
where a.id == authorId
select new
{
id = a.id
};
foreach (var book in books.ToList())
{
var bookdata = await this.getBook(book.id);
result += bookdata.name + ", ";
}
return result;
}
如果你想发出并发的http请求,你可以创建一些任务并使用Task.WhenAll,例如
https://stackoverflow.com/a/30668277/1538039