Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using await inside properties in C# [duplicate]

Possible Duplicate:
How to call an async method from a getter or setter?

I'm trying to implement a property that'll use the Sqlite await inside it:

public int ID {
        get
        {
            if (_id != null)
            {
                return _id;
            }
            if (string.IsNullOrEmpty(ImageName))
            {
                return -1;
            }
            var query = CurrentConnection.Table<Image>().Where(i => i.ImageName == ImageName);
            var result = await query.ToListAsync();
            ...other code

However, since a property is not set to await(tried that, doesn't work), I can't use await inside a property.

Any way to get around this besides using a method instead of a property?

like image 781
jbkkd Avatar asked Dec 05 '12 15:12

jbkkd


People also ask

Can properties be async?

Unlike async constructors, async properties could be added to the language without much difficulty (well, property getters could, at least). Properties are just syntactic sugar for getter and setter methods, and it wouldn't be a huge leap to make these methods async . However, async properties are not allowed.

Is await blocking C#?

The await keyword, by contrast, is non-blocking, which means the current thread is free to do other things during the wait.

How async await works internally?

The async keyword turns a method into an async method, which allows you to use the await keyword in its body. When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete. await can only be used inside an async method.

Does C have async await?

In C. There's no official support for await/async in the C language yet. Some coroutine libraries such as s_task simulate the keywords await/async with macros.


1 Answers

No - there's no such thing as an async property. Even if you could declare an async property, it would have to be declared as having a return value of Task<int> rather than int... otherwise what would you want to return when you hit an await expression?

I would strongly suggest a GetIdAsync method here, assuming you definitely want async behaviour.

like image 63
Jon Skeet Avatar answered Nov 01 '22 02:11

Jon Skeet