c# - 如何正确使用Microsoft.Bcl.Async?

标签 c# wpf asynchronous .net-4.0 async-await

我使用 Microsoft.Bcl.Async package在一个项目中,并且该项目被另一个不使用异步功能的项目引用。

现在我在编译解决方案(或仅编译第二个项目)时收到此错误警告:

The primary reference "XYZ.dll" could not be resolved because it has an indirect dependency on the framework assembly "System.Runtime, Version=1.5.11.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which could not be resolved in the currently targeted framework. ".NETFramework,Version=v4.0". To resolve this problem, either remove the reference "XYZ.dll" or retarget your application to a framework version which contains "System.Runtime, Version=1.5.11.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".

我在这两个项目中都使用了这个 app.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:bcl="urn:schemas-microsoft-com:bcl">
      <dependentAssembly bcl:name="System.Runtime">
        <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.5.16.0" newVersion="2.5.16.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Threading.Tasks" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.5.16.0" newVersion="2.5.16.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

我做错了什么?

我不想引用异步包 dll。

我无法使用 .Net 4.5 目标。必须是 .Net 4。

所有项目的目标框架:.NET Framework 4

最佳答案

总结:

有几个解决方法可供您使用:

  1. Microsoft.Bcl.Async 包安装到引用项目。

  2. Microsoft.Bcl.Build 包安装到引用项目。这包含实际的修复,并且只是一个构建时依赖项。执行此操作时,您必须在项目的 App.Config 中进行适当的绑定(bind)重定向(例如上面列出的内容)- 无论它是类库、Web 项目还是可执行文件。

    <
  3. 如果您不想依赖任何包,请在 Microsoft.Bcl.targets 文件(随 Microsoft.Bcl.Build 一起安装)中获取 PropertyGroup 元素的内容,并将其插入到在最后一个 Import 元素之后引用项目。

注意:无论您在上面选择了哪个选项,当您运送依赖于 Microsoft.Bcl.Async 的库(与旧的 Microsoft.CompilerServices.AsyncTargetingPack 一样)时,您必须运送那些二进制文件(System.Runtime、System.Threading.Tasks、Microsoft.Threading.Tasks.*)与使用您的库的应用程序/包。

说来话长:

正如 Peter 指出的那样,这是一个已知问题,由于它们的设计方式,它只发生在 Microsoft.Bcl.Async 而不是 Microsoft.CompilerServices.AsyncTargetingPack。

Microsoft.Bcl.Async 的部分设计是向后移植(通过 NuGet 包)一些新的 .NET 4.5 程序集(System.Runtime、System.Threading.Tasks),以便它们可以在 4.0 上运行。 MSBuild 不喜欢这样,它会导致它认为引用库已经依赖于来自较新框架版本的程序集。 Microsoft.Bcl.Build 包中的解决方法解决了这个问题。

关于c# - 如何正确使用Microsoft.Bcl.Async?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15551953/

相关文章:

image - Angular2 - 在 ngFor 内异步加载二进制图像数据

c# - 索引时出现错误的请求错误

c# - "FormatException was unhandled by user code"输入字符串的格式不正确

c# - 从 Visual Studio 启动时,WPF 应用程序加载初始窗口的速度非常慢

c# - MVVM WPF - 登录逻辑

c# - 异步任务和锁

c# - 为什么我会收到 StringFormat 错误?

c# - 在 C# 中存储重复的键值对

c# - 从网络摄像头输入以编程方式更新 WPF 图像控件

javascript - 异步函数中并发 Promise 的顺序如何工作?