Search code examples
postsharp

Postsharp: ThreadAffineAttribute and async method


This method throws error: An attempt was made to access the object from an invalid thread.

If I were removed Task.Delay then it would work.

But I need async methods to work.

public async Task<int> Test() {
    await Task.Delay( 100 );
    return 0;
}

Solution

  • If, according to your comments, you don't need your object to be thread-affined, but instead need to make sure it's only accessed by one thread at any given moment, you may consider using the Actor threading model instead (https://doc.postsharp.net/actor).

    Another threading model that may work for you is Synchronized (https://doc.postsharp.net/synchronized), which is basically an exclusive lock.