Questions tagged «c#»

C#(发音为“ See Sharp”)是由Microsoft开发的一种高级,静态类型的多范例编程语言。C#代码通常针对Microsoft的.NET系列工具和运行时,其中包括.NET Framework,.NET Core和Xamarin。使用此标记可解决有关用C#或C#正式规范编写的代码的问题。

1
SignalR .NET客户端连接到Blazor .NET Core 3应用程序中的Azure SignalR服务
我正在尝试在ASP.NET Core 3.0 Blazor(服务器端)应用程序与Azure SignalR服务之间建立连接。最后,我将SignalR客户端(服务)注入到一些Blazor组件中,以便它们可以实时更新我的​​UI / DOM。 我的问题是,.StartAsync()在集线器连接上调用方法时,我收到以下消息: 响应状态代码不表示成功:404(未找到)。 BootstrapSignalRClient.cs 该文件加载了我对SignalR服务的配置,包括URL,连接字符串,键,方法名称和集线器名称。这些设置在静态类中捕获,SignalRServiceConfiguration并在以后使用。 public static class BootstrapSignalRClient { public static IServiceCollection AddSignalRServiceClient(this IServiceCollection services, IConfiguration configuration) { SignalRServiceConfiguration signalRServiceConfiguration = new SignalRServiceConfiguration(); configuration.Bind(nameof(SignalRServiceConfiguration), signalRServiceConfiguration); services.AddSingleton(signalRServiceConfiguration); services.AddSingleton<ISignalRClient, SignalRClient>(); return services; } } SignalRServiceConfiguration.cs public class SignalRServiceConfiguration { public string ConnectionString { get; set; …

4
如何终止SignalR连接?
我正在使用SignalR在网站上传输数据。但是SignalR应该只能在一段时间内发送数据,并且如果该时间段过去了,则应该终止连接。 $.connection.hub.stop()如果请求仍未完成且未完成,则取消停止功能。但是无论发送了多少数据,都应强制取消此请求。 如何杀死 SignalR-Connection?

1
在Powershell中运行时与Visual Studio中运行时的HttpClient并发行为不同
我正在使用MS Graph API将数百万用户从本地AD迁移到Azure AD B2C,以在B2C中创建用户。我已经编写了一个.Net Core 3.1控制台应用程序来执行此迁移。为了加快进度,我正在同时调用Graph API。这很好-有点。 在开发过程中,从Visual Studio 2019运行时,我的性能达到了可接受的水平,但是为了测试,我从Powershell 7中的命令行运行。从Powershell中,对HttpClient的并发调用的性能非常糟糕。从Powershell运行时,HttpClient允许的并发调用数似乎是有限制的,因此,并发批处理中的调用(大于40至50个请求)将开始堆积。它似乎正在运行40至50个并发请求,同时阻止其余请求。 我不是在寻求异步编程方面的帮助。我正在寻找一种方法来解决Visual Studio运行时行为和Powershell命令行运行时行为之间的差异。从Visual Studio的绿色箭头按钮在发布模式下运行的行为符合预期。不从命令行运行。 我用异步调用填充任务列表,然后等待Task.WhenAll(tasks)。每次通话需要300到400毫秒。从Visual Studio运行时,它可以按预期工作。我并发执行1000个调用的批处理,每个处理都在预期的时间内完成。整个任务块比最长的单个调用花费几毫秒的时间。 当我从Powershell命令行运行相同的构建时,行为会改变。最初的40到50个通话会花费300到400毫秒,但是每个单独的通话时间会增加到20秒。我认为这些调用正在序列化,因此在其他等待时一次只执行40到50。 经过数小时的反复试验,我能够将其范围缩小到HttpClient。为了找出问题,我使用执行Task.Delay(300)并返回模拟结果的方法模拟了对HttpClient.SendAsync的调用。在这种情况下,从控制台运行的行为与从Visual Studio运行的行为相同。 我正在使用IHttpClientFactory,甚至尝试调整ServicePointManager的连接限制。 这是我的注册码。 public static IServiceCollection RegisterHttpClient(this IServiceCollection services, int batchSize) { ServicePointManager.DefaultConnectionLimit = batchSize; ServicePointManager.MaxServicePoints = batchSize; ServicePointManager.SetTcpKeepAlive(true, 1000, 5000); services.AddHttpClient(MSGraphRequestManager.HttpClientName, c => { c.Timeout = TimeSpan.FromSeconds(360); c.DefaultRequestHeaders.Add("User-Agent", "xxxxxxxxxxxx"); }) …

2
如果消息处理失败,则再次使用同一消息
我正在使用Confluent.Kafka .NET客户端版本1.3.0。我正在关注文档: var consumerConfig = new ConsumerConfig { BootstrapServers = "server1, server2", AutoOffsetReset = AutoOffsetReset.Earliest, EnableAutoCommit = true, EnableAutoOffsetStore = false, GroupId = this.groupId, SecurityProtocol = SecurityProtocol.SaslPlaintext, SaslMechanism = SaslMechanism.Plain, SaslUsername = this.kafkaUsername, SaslPassword = this.kafkaPassword, }; using (var consumer = new ConsumerBuilder<Ignore, string>(consumerConfig).Build()) { var cancellationToken = new CancellationTokenSource(); …

1
尝试通过属性默认值更改关系时发生意外的InvalidOperationException
在下面的示例代码中,执行此操作时出现以下异常db.Entry(a).Collection(x => x.S).IsModified = true: System.InvalidOperationException:'无法跟踪实体类型'B'的实例,因为已经跟踪了具有键值'{Id:0}'的另一个实例。附加现有实体时,请确保仅附加一个具有给定键值的实体实例。 为什么不添加而不是附加B的实例? 奇怪的是,文档IsModified未指定InvalidOperationException可能的例外。无效的文档或错误? 我知道这段代码很奇怪,但是我写它只是为了了解ef core在某些奇怪的egde情况下是如何工作的。我想要的是一个解释,而不是变通的方法。 using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; class Program { public class A { public int Id { get; set; } public ICollection<B> S { get; set; } = new List<B>() { new B {}, new B …

1
从Asp.Net Core控制器返回IAsyncEnumerable <T>和NotFound
对于返回an IAsyncEnumerable&lt;T&gt;和a NotFoundResult但仍以异步方式处理的控制器操作,正确的签名是什么? 我使用了此签名,由于IAsyncEnumerable&lt;T&gt;无法等待,因此无法编译: [HttpGet] public async Task&lt;IActionResult&gt; GetAll(Guid id) { try { return Ok(await repository.GetAll(id)); // GetAll() returns an IAsyncEnumerable } catch (NotFoundException e) { return NotFound(e.Message); } } 这个编译很好,但是它的签名不是异步的。因此,我担心它是否会阻塞线程池线程: [HttpGet] public IActionResult GetAll(Guid id) { try { return Ok(repository.GetAll(id)); // GetAll() returns an IAsyncEnumerable } catch (NotFoundException e) …

3
未检查的uint的C#溢出行为
我已经在https://dotnetfiddle.net/测试此代码: using System; public class Program { const float scale = 64 * 1024; public static void Main() { Console.WriteLine(unchecked((uint)(ulong)(1.2 * scale * scale + 1.5 * scale))); Console.WriteLine(unchecked((uint)(ulong)(scale* scale + 7))); } } 如果我使用.NET 4.7.2进行编译,则会得到 859091763 7 但是如果我使用Roslyn或.NET Core,我会得到 859091763 0 为什么会这样?
10 c#  .net  overflow  roslyn  uint 

1
Hijri日期到公历日期是否有正确的转换器
我从事许多日期转换项目。例如,我研究太阳历,以及如何将其转换为公历日期,反之亦然。就一年中的天数而言,太阳历(波斯历)与公历几乎相似[有无le]。 但是我最近在一个与阴历有关的项目上工作。在研究农历时,我意识到没有任何一种逻辑方法可以将农历系统转换为太阳系(至少据我所知)。 这是我研究过的一些参考链接: 无法将回历日期转换为公历日期(C#) 将回历日历中的日期转换为公历,反之亦然 回历日期到公历使用DateTime.Parse 转换回历日期为格里高利历 当我按照上面的链接进行培训和测试人员介绍算法时,我注意到它们都不是绝对正确的。 只需说一下,只要将"1441/02/30" [Safar 30th]您要尝试的每种方法转换为公历日期即可。 下图对于上述示例很有帮助。 我在这里输入了一些测试代码,但失败了: CultureInfo arSA = new CultureInfo("ar-SA"); arSA.DateTimeFormat.Calendar = new HijriCalendar(); var dateValue = DateTime.ParseExact("1441/02/30", "yyyy/MM/dd", arSA); return dateValue.ToString(); 上面代码的错误: 日历System.Globalization.HijriCalendar不支持由字符串表示的DateTime。 HijriCalendar hc = new HijriCalendar(); DateTime date = new DateTime(1441, 2, 30, hc); return date.ToString(); 上面代码的错误: “第二个月的日期必须在1到29之间。” string …
10 c#  hijri 

3
如何在blazor服务器端本地化验证消息(DataAnnotationsValidator)
我在最新版本的VS 2019中使用blazor 3.1。 到目前为止,我已经可以本地化页面标签(标题,表格字段等)。 在ListEmployee.razor页面中,我能够本地化表格标题等。在AddEmplyeeValidation.razor页面中,我能够本地化表单标签,但是在本地化验证消息时遇到问题。 用于验证消息的Employee.cs验证消息是在此文件和Resources/Data文件夹中定义的,其名称定义为Data.Employee.ar.resx并且Data.Employee.ar.resx无法正常工作 使用System.ComponentModel.DataAnnotations; 命名空间BlazorSPA1.Data {公共类Employee {[MaxLength(50)]公共字符串ID { 组; } [Required (ErrorMessage ="Name is RRRequired")] [StringLength(20, ErrorMessage = "Name is too long.")] public string Name { get; set; } [Required] [StringLength(20)] public string Department { get; set; } [MaxLength(100)] public string Designation { get; set; } [MaxLength(100)] …

5
C#8中的不可为空的引用类型在运行时可以为null吗?
在我看来,真的不能保证非空变量永远不会有null。想象一下,我有一个具有不为空的属性的类: public class Foo { public Foo(string test) { Test = test; } public string Test {get;set;} } 现在看起来好像现在不能为空。但是,如果我们用另一个不使用可为空的上下文的库引用该类,则没有什么可以阻止它在其中发送null的。 那是正确的还是有一些运行时检查也可以确保这一点?

1
为什么用相同的输入调用Vector2.Normalize()的结果34次后会更改?
这是一个简单的C#.NET Core 3.1程序,该程序System.Numerics.Vector2.Normalize()循环调用(每次调用都具有相同的输入),并打印出结果归一化向量: using System; using System.Numerics; using System.Threading; namespace NormalizeTest { class Program { static void Main() { Vector2 v = new Vector2(9.856331f, -2.2437377f); for(int i = 0; ; i++) { Test(v, i); Thread.Sleep(100); } } static void Test(Vector2 v, int i) { v = Vector2.Normalize(v); Console.WriteLine($"{i:0000}: {v}"); } …
10 c#  .net  .net-core 

3
返回IAsyncEnumerable的方法是否有明确的命名约定?
在C#5引入async和之后await用于异步编程模型之后,C#社区达成了一种命名约定,即向返回等待类型的方法添加“ Async”后缀,如下所示: interface Foo { Task BarAsync(); } 从那时起,许多异步代码分析器(基于Roslyn的和基于非Roslyn的)都被编写为在异步编程周围检测代码气味时依赖于此命名约定。 既然C#8引入了异步枚举的概念,它们本身不是可以等待的,但是可以与结合使用await foreach,似乎有两种方法可以返回命名方法IAsyncEnumerable: interface Foo { // No "Async" suffix, indicating that the return value is not awaitable. IAsyncEnumerable&lt;T&gt; Bar&lt;T&gt;(); } 要么 interface Foo { // With "Async" suffix, indicating that the overall logic is asynchronous. IAsyncEnumerable&lt;T&gt; BarAsync&lt;T&gt;(); } 是否有关于上述选项的明确的命名约定准则(来自C#语言团队,.NET Foundation或其他机构),例如C#5命名约定是如何明确标准化的,而不是由程序员根据意见进行判断的?
10 c#  c#-8.0 

1
安装NuGet软件包时,可以解决这些.dll问题吗?
我从阅读与我类似的建议问题开始,但是没有解决方案:为什么MSTest.TestAdapter将其DLL添加到我的NuGet包中? 快速问题描述 我写了一个NuGet包,每一次我安装它,NUnit和NUnit3TestAdapter .dll的被添加到我安装的项目。我想找到解决此问题的解决方案。 复制步骤 我推了两个git存储库,它们再现了我正在描述的问题。 ClientLibrary/ MainFramework(我从中生成NuGet包的项目)-https: //github.com/harbourc/client-library-repro-nuget-issue TargetProject(要安装该软件包的项目)-https://github.com/harbourc/target-project-repro-nuget-issue 您可以克隆两个存储库,还原它们的NuGet包,并按以下步骤重现该问题: 在client-library-repro-nuget-issue / ClientLibrary /中找到ClientLibrary.1.0.0.nupkg 打开包管理器控制台以执行target-project-repro-nuget-issue并运行 Install-Package C:\Path\To\client-library-repro-nuget-issue\ClientLibrary\ClientLibrary.1.0.0.nupkg 注意NUnit和NUnit3TestAdapter .dll被加入的TargetProject-尽管TargetProject已经有了NUnit和NUnit3TestAdapter安装。 更长的概述 我创建了自己的NuGet软件包供内部使用,名为ClientLibrary,并且尝试将其安装到另一个项目上TargetProject。这是结构的快速分解: FullSolution.sln MainFramework.csproj ClientLibrary.csproj-&gt; .nupkg由此产生 单独的项目: TargetProject.sln TargetProject.csproj-&gt;安装.nupkg到此 ClientLibrary引用MainFramework并使用了许多方法MainFramework。 当安装ClientLibrary.1.0.0.nupkg到TargetProject,下面.dll的越来越添加到TargetProject: nunit.engine.api.dll nunit.engine.dll NUnit3.TestAdapter.dll NUnit3.TestAdapter.pdb 如果删除这些.dll,一切正常,因为TargetProject无论如何已经安装了这些软件包。它们不是必需的,在安装时必须删除它们只是很烦人。 这是我将ClientLibraryNuGet包添加到的方式TargetProject: 生成ClientLibrary和MainFramework项目以生成其.dll 将目录更改为ClientLibrary文件夹并运行nuget spec .nuspec 文件生成: &lt;?xml version="1.0"?&gt; &lt;package &gt; &lt;metadata&gt; &lt;id&gt;ClientLibrary&lt;/id&gt; &lt;version&gt;1.0&lt;/version&gt; &lt;title&gt;Client …
10 c#  .net  dll  nuget 

8
如何在C#中使用正则表达式获取某些特定单词之前的数字?
我们将使用下面的正则表达式来获取单词之前的数字。 范例: 838123 someWord 8 someWord 12 someWord (\d+)\s*someWord 但是有时数字和单词之间会出现任何东西。请参见下面的示例行。 例如: someword 12的43434 someword 2323 new someword 如何使用正则表达式获取该单词之前的确切数字? 请给我您的建议。
10 c#  .net  regex 

1
mscorlib的`System.Boolean`如何避免结构布局循环?
System.Boolean参考源网站上的的源代码指出的实例struct Boolean仅包含一个bool字段private bool m_value: https://referencesource.microsoft.com/#mscorlib/system/boolean.cs,f1b135ff6c380b37 namespace System { using System; using System.Globalization; using System.Diagnostics.Contracts; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public struct Boolean : IComparable, IConvertible #if GENERICS_WORK , IComparable&lt;Boolean&gt;, IEquatable&lt;Boolean&gt; #endif { private bool m_value; internal const int True = 1; internal const int False = 0; internal const String TrueLiteral = "True"; …
10 c# 

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.