DbContext与IOC与多线程

1、先看报错日志:

 An exception occurred while iterating over the results of a query for context type 'Mes.Data.MesContext'.
System.InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
   at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext() A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.|Microsoft.EntityFrameworkCore.Query|contextType=Mes.Data.MesContext, newline=
, error=System.InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.

微软官方明确不支持多线程,真是败笔。不支持单例复用。每次都是需要实例化(不用担心资源消耗问题)。但是前面的IOC 仓储代码需要丢弃,这好蛋疼
2、解决方案看代码:

public class ServiceLocator
    {
        public static IServiceProvider Services { get; private set; }
        public static void SetServices(IServiceProvider services)
        {
            Services = services;
        }
        public static T GetService()
        {
            return Services.GetService();
        }
    }
services.AddDbContext(options =>
{
options.UseSqlServer(hostContext.Configuration.GetConnectionString("Mes")).UseLoggerFactory(NLoggerFactory).UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
},ServiceLifetime.Transient);                    
ServiceLocator.SetServices(services.BuildServiceProvider());
//注意其他仓储,服务层全部注册为ServiceLifetime.Transient模式
//调用代码(多线程里面每次需要调用,不能复用,没有测试性能问题):
//_isysOpcCodeService = ServiceLocator.GetService();
//_isysOpcCodeService.GetAll().Take(3).ToList();

WPF 与 IOC与Nlog

1、新建一个WPF core项目

2、删除App.xaml之中StartupUri=”MainWindow.xaml”代码

3、修改app代码

public partial class App : Application
{
public IConfiguration Configuration;
private IServiceProvider _serviceProvider;

protected override void OnStartup(StartupEventArgs e)
{
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

Configuration = builder.Build();

var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);

_serviceProvider = serviceCollection.BuildServiceProvider();

var mainWindow = _serviceProvider.GetRequiredService();
mainWindow.Show();
}
private void ConfigureServices(IServiceCollection services)
{
services.AddLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
logging.AddNLog(Configuration.GetSection("Logging"));
});
services.AddSingleton(typeof(MainWindow));
services.AddSingleton();
}
}

4、修改windows代码

public partial class MainWindow : Window
{
private readonly ILogger _logger;
private readonly IOpcService _opcService;
public MainWindow(ILogger logger, IOpcService opcService )
{
_logger = logger;
_opcService = opcService;
_logger.LogDebug("开始");
InitializeComponent();
}
}

5、执行F5

appsettings.json参考微软教程

nlog.config参考https://github.com/NLog/NLog/wiki/Getting-started-with-.NET-Core-2—Console-application

LINUX常用命令

复制文件夹文件

\cp -rf /usr/share/nginx/html/glcool/wordpress/mystaticsite/* .

防火墙

systemctl stop firewalld 
firewall-cmd --get-active-zones
firewall-cmd --get-zone-of-interface=eth0
firewall-cmd --zone=public --list-ports
firewall-cmd --zone=public --add-port=5060-5059/tcp --permanent
firewall-cmd --reload    

端口

lsof -i:8080
netstat -tunlp
netstat -tunlp | grep 端口号

MYSQL

mysql -h 127.0.0.1 -p 3306 -u root -p

权限

chown -R www-data:www-data /root

chmod -R +777 /root

GIT常用命令

删除手动删除的文件

git add -A .

git commit -m “sc”

git push origin master

———————-

git clone 克隆远程地址

出现错误的原因是github中的README.md文件不在本地代码目录中
使用如下命令:git pull –rebase origin master
然后再进行上传: git push -u origin master


删除文件夹所有文件

git rm -r 文件夹

windows10-tensorflow2安装

0、CMD管理员打开,先安装python3.75

安装virtualenv

1、pip3 install -U pip virtualenv -i http://pypi.douban.com/simple –trusted-host pypi.douban.com

创建一个虚拟环境

2、virtualenv –system-site-packages -p python D:\tf

激活虚拟环境/在虚拟环境中安装软件包,而不影响主机系统设置。从升级开始pip/并在以后退出virtualenv

3、D:\tf\Scripts\activate(注意是执行这个文件)

pip install –upgrade pip
pip list
deactivate

4、在python虚拟机环境安装TensorFlow CPU包

 执行 D:\tf\Scripts\activate

pip install –upgrade tensorflow -i http://pypi.douban.com/simple –trusted-host pypi.douban.com

验证安装:

python -c “import tensorflow as tf;print(tf.reduce_sum(tf.random.normal([1000, 1000])))”

 

C# Rabbitmq RPC模式服务器超时解决方案

利用2个task实现,看红字,直接看代码
public string Call(string rpc_queue, byte[] obj)
{
string rstr = “no”;
var channel = this.GetModel(RpcChannel); channel.ContinuationTimeout = TimeSpan.FromSeconds(10);
channel.BasicPublish(exchange: “”, routingKey: rpc_queue, basicProperties: props, body: obj);
channel.BasicConsume(consumer: consumer, queue: replyQueueName, autoAck: true);
Task[] tasks = new Task[2];
tasks[0] = Task.Run(async () =>
{
await Task.Delay(6000);//超时
respQueue.Add(rstr);
//respQueue.CompleteAdding();
});
tasks[1] = Task.Run(() =>
{
rstr = respQueue.Take();
});
try
{
Task.WaitAll(tasks);
}
catch (AggregateException ae)
{
foreach (var ex in ae.InnerExceptions)
Console.WriteLine(” {0}: {1}”, ex.GetType().Name, ex.Message);
}
return rstr;
}

C#动态编译表达式

下面是原始方案
public object ComplierCode(string expression, ILogService logService, out string errorString)
{
string code = WrapExpression(expression);
object retvalue = null;
errorString = “”;
CSharpCodeProvider csharpCodeProvider = new CSharpCodeProvider();
try
{
//编译的参数
CompilerParameters compilerParameters = new CompilerParameters
{
CompilerOptions = “/t:library”,
GenerateInMemory = true
};
//开始编译
CompilerResults compilerResults = csharpCodeProvider.CompileAssemblyFromSource(compilerParameters, code);
if (compilerResults.Errors.Count > 0)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i 0 ? “;” : “”);
sb.Append(compilerResults.Errors[i].ErrorText);
}
errorString = sb.ToString();
throw new Exception(“编译出错!” + sb.ToString());
}

Assembly assembly = compilerResults.CompiledAssembly;
Type type = assembly.GetType(“ExpressionCalculate”);
MethodInfo method = type.GetMethod(“Calculate”);
retvalue = method.Invoke(null, null);
}
catch (Exception ex)
{
logService.WriteLog(“编译出错,code=” + code, ex);
}
finally
{
csharpCodeProvider.Dispose();
}
return retvalue;
}

private string WrapExpression(string expression)
{
string code = @”
using System;

class ExpressionCalculate
{
public static object Calculate()
{
return {0};
}
}
“;
return code.Replace(“{0}”, expression);
}
其他方案:https://github.com/davideicardi/DynamicExpresso

Linux CentOS7安装NET Core

sudo rpm -Uvh https://packages.microsoft.com/config/rhel/7/packages-microsoft-prod.rpm
sudo yum update
sudo yum install dotnet-sdk-2.2-2.2.108-1

安装守护进程
yum install supervisor
systemctl enable supervisord.service
systemctl start supervisord.service
systemctl status supervisord.service
vi /etc/supervisord.conf(修改9001端口注释,打开防火墙,重启)
systemctl restart supervisord.service
参考:https://my.oschina.net/weidedong/blog/747428

C#动态执行javascript

Create a file in Notepad with only these contents:

class EvalClass { function Evaluate(expression: String) { return eval(expression); } }
Save the file as C:\MyEval.js

Open a VS2005 Command Prompt (Start, Programs, VS2005, VS2005 Tools)

Type Cd\ to get to C:\

Type

jsc /t:library C:\MyEval.js
A new file is created named MyEval.dll.

Copy MyEval.dll to the project and reference it (also reference Microsoft.Jscript.dll).

Then you should be able to call it like this:

Dim jScriptEvaluator As New EvalClass
Dim objResult As Object
objResult = jScriptEvaluator.Evaluate(“1==1 && 2==2”)
其他方式:https://github.com/davideicardi/DynamicExpresso(支持netcore)

debian9安装mariadb导致密码无效问题

debian9默认就是mariadb这个数据库,mysql一样
sudo apt install mariadb-server
sudo -i
mysql -u root -p
1 use mysql; 然后敲回车
2 update user set authentication_string=password(“你的密码”) where user=”root” 然后敲回车
3 flush privileges 然后敲回车上面操作都没有用的
#select user,plugin from user后看看,错误原因是因为plugin root的字段是auth_socket,那我们改掉它为下面的mysql_native_password
update user set authentication_string=password(“123456”),plugin=’mysql_native_password’ where user=’root’;
flush privileges;
到处都是坑
参考:http://blog.sina.com.cn/s/blog_7c987bee0102yz76.html