一般方法怎么样?
private async Task<T> GetAsync<T>(string uri)
{
var client = GetHttpClient(uri);
var content = await client.GetStringAsync(uri);
var serializer = new JavaScriptSerializer();
var t = serializer.Deserialize<T>(content);
return t;
}
通常情况下,你应该把这个方法到另一个类,并使其public
,以便它可以在不同的类中的方法可以使用。
关于调用此方法的方式,你可以尝试以下方法:
// I capitalized the first letter of the method,
// since this is a very common convention in .NET
public Patron GetPatronById(string barcode)
{
string uri = "patrons/find?barcode=" + barcode;
var Patron = GetAsync<Patron>(uri).Result;
return Patron;
}
注:在上面的代码中我认为你没有移动GetAsync
到另一个类。如果你移动它,那么你必须稍作改动。
更新
我不跟着你用你的音符的意思。我是否也需要让GetPatronById成为一项任务功能 - 就像Yuval在下面做的那样?
我的意思是这样的:
// The name of the class may be not the most suitable in this case.
public class Repo
{
public static async Task<T> GetAsync<T>(string uri)
{
var client = GetHttpClient(uri);
var content = await client.GetStringAsync(uri);
var serializer = new JavaScriptSerializer();
var t = serializer.Deserialize<T>(content);
return t;
}
}
public Patron GetPatronById(string barcode)
{
string uri = "patrons/find?barcode=" + barcode;
var Patron = Repo.GetAsync<Patron>(uri).Result;
return Patron;
}
对象是根对象吗? https://msdn.microsoft.com/zh-cn/library/system.object(v=vs.110).aspx –
您不应该对'GetAsync'的结果使用'.Result'。如果你在UI线程上调用它,你会遇到死锁。 –
为什么getPatronById不是异步?它应该是异步的,并且你不使用'.Result'或'GetAsync'不应该是异步的,你应该使用'WebClient'而不是'HttpClient'并且使用同步方法。使用'.Result'可能会导致程序锁定。 –