访问时,类变量的值始终为 null



我正在函数中进行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
}

如果您希望任务在后台运行并仅在任务完成后打印"name"的值,则最佳选择是使用"异步"。等待'。 为此,您需要使方法异步并显式等待任务:

// 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
}

最新更新