C# 使代码不工作的异步函数
首先,为标题向我道歉。。。我还没有找到一件适合我的单箱:P 首先,我需要下载一个C# 使代码不工作的异步函数,c#,windows-10,c#-5.0,windows-10-mobile,C#,Windows 10,C# 5.0,Windows 10 Mobile,首先,为标题向我道歉。。。我还没有找到一件适合我的单箱:P 首先,我需要下载一个INI文件来填充字典。为此,我有以下课程: public class Properties : INotifyPropertyChanged { private Dictionary<string, string> _properties; public Properties() { _properties = new Dictionary<string,
INI
文件来填充字典。为此,我有以下课程:
public class Properties : INotifyPropertyChanged
{
private Dictionary<string, string> _properties;
public Properties()
{
_properties = new Dictionary<string, string>();
}
public async void Load(string uri)
{
Stream input = await connection(uri);
StreamReader rStream = new StreamReader(input);
string line;
while((line = rStream.ReadLine()) != null)
{
if(line != "")
{
int pos = line.IndexOf('=');
string key = line.Substring(0, pos);
string value = line.Substring(pos + 1);
_properties.Add(key, value);
Debug.WriteLine("Key: " + key + ", Value: " + value);
}
}
Debug.WriteLine("Properties dictionary filled with " + _properties.Count + " items.");
}
public async Task<Stream> connection(string uri)
{
var httpClient = new HttpClient();
Stream result = Stream.Null;
try
{
result = await httpClient.GetStreamAsync(uri);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
Debug.WriteLine(ex.HResult);
}
return result;
}
public string getValue(string key)
{
string result = "";
try
{
result = _properties[key];
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
Debug.WriteLine(ex.HResult);
result = "Not found";
}
return result;
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged([CallerMemberName]string propertyName = "")
{
var Handler = PropertyChanged;
if (Handler != null)
Handler(this, new PropertyChangedEventArgs(propertyName));
}
}
UserControl
的构造函数使用MainPage
作为回调
和类Properties
来查找下载XML
文件的URL
所发生的情况是,由于Properties.Load()
是一个异步方法,因此被调用,然后执行剩余的行,当程序完成时,返回到Load()
并填充字典。
由于Home
构造函数依赖于属性的值
,因此我得到一个异常
我曾尝试创建async void
s,分配不同的优先级,以强制程序先运行一件事,然后运行其余的事情,但也没有成功
因此,总而言之,我需要确保首先填写属性,,有人知道怎么做吗
提前谢谢 Eva如果要等待加载方法完成,则必须更改此方法以返回任务
public async Task LoadAsync(string uri)...
最好将代码放在页面的LoadedEventHandler中,并使此方法异步。之后,您将能够等待Properties.Load方法
如果要在构造函数中调用此方法,可以这样做:
Task.Run(async () =>{
var task = p.LoadAsync().ConfigureAwait(false);
await task;
}).Wait()
但您必须注意,如果in-LoadAsync方法将在未禁用上下文切换(ConfigureAwait)的情况下等待,则可能会出现死锁。非常感谢@razor118!我终于解决了这个问题:)
Task.Run(async () =>{
var task = p.LoadAsync().ConfigureAwait(false);
await task;
}).Wait()