Can I simplify the code?
You can both simplify it, and make it more correct. There are a few problems with the code as-written:
IsLoading
is a UI-bound property, so it should be updated on the UI thread, not a background thread. Some frameworks like WPF on Windows allow you to bend the rules, but other XAML-based frameworks do not.
- The code currently will not ever set
IsLoading
to false
if the loading fails.
Task.Factory.StartNew
should be avoided; it's a dangerous, low-level method. Use Task.Run
if you need to run a method on a background thread.
async Task<T> Load<T>(Func<T> function)
{
IsLoading = true;
try
{
return await Task.Run(function);
}
finally
{
IsLoading = false;
}
}
Is there a way I could make this method more generic so that I could pass methods with parameters as well?
You can use lambdas for this:
string someString = await Load(() => GetString("string"));
string someString = await Load(() => GetString("string", 1));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…