Reputation: 123
I've got an ObservableCollection
in an interface and I'm using it with a RestApi-Request
. It has some Await functions and it must be async. But there's an error.
Here's the interface:
public interface IDbConnection
{
ObservableCollection<Einkauf> GetEinkauf();
}
Here's the part from the class it is using:
public partial class RestView : IDbConnection
{
private ObservableCollection<Einkauf> _einkauf;
private const string Url = "http://localhost:3003/einkauf";
private HttpClient _client = new HttpClient();
public RestView ()
{
InitializeComponent ();
}
public async ObservableCollection<Einkauf> GetEinkauf()
{
var content = await _client.GetStringAsync(Url);
var einkauf = JsonConvert.DeserializeObject<List<Einkauf>>(content);
_einkauf = new ObservableCollection<Einkauf>(einkauf);
speisenListe.ItemsSource = _einkauf;
return _einkauf;
}
}
The GetEinkauf
is underlined and it says:
CS1983 C# The return type of an async method must be void, Task or Task<T>
Does anybody know how to fix this?
Upvotes: 0
Views: 343
Reputation: 169200
If GetEinkauf
is supposed to be implemented as an asynchronous method, you should change it return type to Task<ObservableCollection<Einkauf>>
and also change its name to GetEinkaufAsync to follow the naming convention for asynchronous methods:
public interface IDbConnection
{
Task<ObservableCollection<Einkauf>> GetEinkaufAsync();
}
public async Task<ObservableCollection<Einkauf>> GetEinkaufAsync()
{
var content = await _client.GetStringAsync(Url);
var einkauf = JsonConvert.DeserializeObject<List<Einkauf>>(content);
_einkauf = new ObservableCollection<Einkauf>(einkauf);
speisenListe.ItemsSource = _einkauf;
return _einkauf;
}
You could then await
the method from any method marked as async
:
var collection = await GetEinkaufAsync();
If another class implements the IDbConnection
interface in a synchronous fashion for some reason, it could use the Task.FromResult
method to return a Task<ObservableCollection<Einkauf>>
:
public class SomeOtherClass : IDbConnection
{
public Task<ObservableCollection<Einkauf>> GetEinkaufAsync()
{
return Task.FromResult(new ObservableCollection<Einkauf>());
}
}
Upvotes: 1
Reputation: 89102
public interface IDbConnection
{
Task<ObservableCollection<Einkauf>> GetEinkauf();
}
public async Task<ObservableCollection<Einkauf>> GetEinkauf()
{
...
}
Upvotes: 2