gpt4 book ai didi

c# - 添加单例 Kafka 生产者 : attempted to read or write protected memory

转载 作者:行者123 更新时间:2023-12-04 15:41:02 27 4
gpt4 key购买 nike

在 .net core Startup.cs ConfigureServices 方法中,我将 kafka 生产者实例注册为单例,然后我将对象作为参数传递给中间层任何类的构造函数作为接口(interface)。在某些情况下,我会收到“尝试读取或写入 protected 内存。这通常表明其他内存已损坏。”错误。

services.AddSingleton<IProducer<Null, string>>(provider => new ProducerBuilder<Null, string>(conf).Build());

using (IProducer<Null, string> producer = new ProducerBuilder<Null, string>(conf).Build())
{
services.AddSingleton<IProducer<Null, string>>(provider => producer);
}

这些代码有什么区别。
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// ... some codes
services.AddSingleton<IProducer<Null, string>>( provider => new ProducerBuilder<Null, string>(conf).Build());

using (IProducer<Null, string> producer = new ProducerBuilder<Null, string>(conf).Build())
{
services.AddSingleton<IProducer<Null, string>>(provider => producer);
}
}
}

错误位置:
public MessageMutation(IHubContext<MessageHub, ITypedHubClient> messageContext, IProducer<Null, string> producer)
{
// some codes...

producer.Produce("my-topic", new Message<Null, string> { Value = message.Value }, handler);

// some codes..
}

最佳答案

错误可能是因为您正在处置您的生产者。单例对象应该具有应用程序的生命周期(这基本上是单例的定义)。
using(IProducer<Null, string> producer = new ProducerBuilder<Null, string>(conf).Build())是简写(语法糖)

IProducer<Null, string> producer = null;
try
{
producer = new ProducerBuilder<Null, string>(conf).Build();

// do sth
}
finally
{
producer?.Dispose();
}

但是当你处理一个对象时,你释放了它的资源,所以它之后不能实际使用

关于c# - 添加单例 Kafka 生产者 : attempted to read or write protected memory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57779159/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com