Why is the compiler optimizing out the parameters

2019-08-05 18:26发布

I started using a Web API cache which I add to particular methods by using an aspect [Cache]. Everything worked great. Later on I changed this method to be async, but since then the compiler started throwing following warnings:

The parameter 'region' of method 'GetTree(System.String, System.String, System.String[])' has been optimized out by the compiler and will not be available to the aspect. Disable compiler optimizations to access the parameter.

Here you can see an example of how I am using Postsharp:

[Cache]
public async Task<IEnumerable<Node>> GetTree(            
[FromUri] string region,
[FromUri] string language,
[FromUri] string[] networks)
{
 ...
 await ...
}

What do I need to do in order to get rid of the warning?

1条回答
The star\"
2楼-- · 2019-08-05 18:59

The C# compiler optimizations remove the parameters from the state machine class if these parameters are not used anywhere inside the async method. This happens regardless of whether you use PostSharp or not. PostSharp shows you the warning to notify that the removed parameters cannot be accessed inside the aspect.

It's recommended to upgrade to the latest build of PostSharp - the newer versions can handle this issue by re-introducing the missing parameters back into the state machine.

If you cannot upgrade, then the workaround is to disable "Optimize code" in the build page of the project properties for release builds (it's disabled for debug builds by default).

查看更多
登录 后发表回答