Postsharp:ThreadAffineAttribute 和异步方法

Postsharp: ThreadAffineAttribute and async method

此方法抛出错误:An attempt was made to access the object from an invalid thread.

如果我被删除了 Task.Delay 就可以了。

但我需要异步方法才能工作。

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

如果您需要 async thread-affine 类型,则只能从 single-threaded 上下文中调用它们,例如 UI 上下文或 AsyncContext

但是,在 thread-affine 类型上需要 async 的情况极为罕见。我会重新考虑 thread-affinity 要求。

如果根据您的意见,您不需要对象是 thread-affined,而是需要确保它在任何给定时刻仅由一个线程访问,您可以考虑使用 Actor改为线程模型 (https://doc.postsharp.net/actor).

另一种可能适合您的线程模型是同步 (https://doc.postsharp.net/synchronized),它基本上是一个独占锁。