我正在函数中进行api调用,并在该函数中更新类变量(名称)的值。现在,当我检查该变量的值时,就可以了。但是,当我尝试在同一类中的其他任何地方访问它时,它什么也没有返回。我已经尝试了所有可能的解决方案。这是代码。
private void PopulateName()
{
try
{
string data1 = WebOp.baseUrl1 + "" + Const.action + "=" + Const.productByCategory + "" +
"&" + Const.category_id + "=" + category_id;
System.Threading.Tasks.Task.Run(() =>
{
RunOnUiThread(() => { progressDialog.Show(); });
WebOp webOp = new WebOp();
String str = webOp.doPost1(data1, this);
JObject jobj = JObject.Parse(str);
string status = jobj[Const.status].ToString();
if (status.Equals(Const.success))
{
try
{
string data = jobj[Const.data].ToString();
myDto = JsonConvert.DeserializeObject<List<ProductDto>>(data)[0];
name = myDto.thecategory_name;
Console.WriteLine("Check value:" + name); //returns the value fine
RunOnUiThread(() =>
{
progressDialog.Dismiss();
});
}
catch (Exception e)
{
Console.WriteLine(e + "");
RunOnUiThread(() => { progressDialog.Dismiss(); });
}
}
else
{
RunOnUiThread(() =>
{
progressDialog.Dismiss();
});
}
}).ConfigureAwait(false);
}
catch (Exception e1)
{
Console.WriteLine(e1 + "");
}
Console.WriteLine("Check again:" + name); //returns nothing
}
答案 0 :(得分:0)
如果您希望任务在后台运行并仅在任务完成后才打印“名称”的值,则最佳选择是使用“异步..等待”。 为此,请使您的方法异步并明确等待任务:
// declare the method as Async using a return type of 'Task'
private async Task PopulateName()
{
try
{
string data1 = WebOp.baseUrl1 + "" + Const.action + "=" + Const.productByCategory + "" +
"&" + Const.category_id + "=" + category_id;
// explicitly await the Task...
await System.Threading.Tasks.Task.Run(() =>
{
RunOnUiThread(() => { progressDialog.Show(); });
WebOp webOp = new WebOp();
String str = webOp.doPost1(data1, this);
JObject jobj = JObject.Parse(str);
string status = jobj[Const.status].ToString();
if (status.Equals(Const.success))
{
try
{
string data = jobj[Const.data].ToString();
myDto = JsonConvert.DeserializeObject<List<ProductDto>>(data)[0];
name = myDto.thecategory_name;
Console.WriteLine("Check value:" + name); //returns the value fine
RunOnUiThread(() =>
{
progressDialog.Dismiss();
});
}
catch (Exception e)
{
Console.WriteLine(e + "");
RunOnUiThread(() => { progressDialog.Dismiss(); });
}
}
else
{
RunOnUiThread(() =>
{
progressDialog.Dismiss();
});
}
}).ConfigureAwait(false);
}
catch (Exception e1)
{
Console.WriteLine(e1 + "");
}
Console.WriteLine("Check again:" + name); //returns nothing
}