我知道hangfire 不会在与 ASP.NET 相同的上下文中运行,并且它有自己的线程池,但我应该在后台作业中使用变量。这是可以理解的,因为事实上,这些作业可能不在同一台服务器上运行。这意味着如果我执行_locked = false;(in Checker()),它将永远不会被应用,因为它在另一个上下文中运行。对于 来说BackgroundJob.Enqueue(() => Start(bot));,如果它是一个重复性作业(cron 作业),那么我在内部使用的那些变量总是会在弹出的每个 cron 作业上重置。
在这种情况下我该如何使用变量?
private UpdateSubscription _subscription;
private StringBuilder _sb = new StringBuilder();
private bool _locked = false;
public void RunStart(Bot bot)
{
BackgroundJob.Enqueue(() => Start(bot));
}
public void Start(Bot bot)
{
ApplyCredentialsOnClient();
var lastKnownKline = _client.GetKlines(bot.CryptoPair.Symbol, bot.TimeInterval.Interval, limit: 2).Data.First();
_subscription = _socketClient.SubscribeToKlineUpdates(bot.CryptoPair.Symbol, bot.TimeInterval.Interval, async data =>
{
if (data.Data.Final)
{
_logger.LogError($"Final | Open time: {data.Data.OpenTime.ToLocalTime()}");
}
if (lastKnownKline.OpenTime != data.Data.OpenTime)
{
// Static
_logger.LogError($"Static …Run Code Online (Sandbox Code Playgroud) 首先,我决定使用 Hangfire,因为它可以在不同的 Windows 服务中或实际上在不同的服务器上运行代码。我可以使用Task类轻松执行我的任务,但我的逻辑将在很长一段时间内 24/7 运行,直到它被用户停止,我认为任务无法处理这个。这就是我使用 Hangfire 的原因。我对不同的解决方案持开放态度。更具体地说,我的逻辑是使用 Web 套接字 24/7 全天候监控内容。
如果你看看我下面的代码,它有 Run 方法,它在 Hangfire 的 BackgroundJob 中生成一个新的机器人。问题是,当我必须停止一个特定的机器人(比如“机器人 1”)时,它应该以某种方式识别当前没有的机器人。
Hangfire 的文档不完整,或者至少我不明白如何从所写的内容中做到这一点。https://docs.hangfire.io/en/latest/background-methods/using-cancellation-tokens.html
private UpdateSubscription _subscription;
private readonly CancellationTokenSource _cts = new CancellationTokenSource();
public async Task RunAsync(string botName)
{
var jobId = BackgroundJob.Enqueue(() => StartAsync(botName, _cts.Token));
await _cache.SetAsync($"bot_{botName.Replace(" ", "_")}", jobId);
}
public void Start(Bot bot, CancellationToken token)
{
// heavy logic
_subscription = _socketClient.SubscribeToKlineUpdates(bot.CryptoPair.Symbol, bot.TimeInterval.Interval /*KlineInterval.OneHour*/, async data =>
{
... logic ...
if (token.IsCancellationRequested)
{
await …Run Code Online (Sandbox Code Playgroud) 我想计算平均绝对偏差,我目前正在使用来自 Stack Overflow(链接在这里)的以下类,由Alex发布:
public class MovingAverageCalculator
{
private readonly int _period;
private readonly double[] _window;
private int _numAdded;
private double _varianceSum;
public MovingAverageCalculator(int period)
{
_period = period;
_window = new double[period];
}
public double Average { get; private set; }
public double StandardDeviation
{
get
{
var variance = Variance;
if (variance >= double.Epsilon)
{
var sd = Math.Sqrt(variance);
return double.IsNaN(sd) ? 0.0 : sd;
}
return 0.0;
}
}
public double Variance …Run Code Online (Sandbox Code Playgroud) 我正在开始使用Serilog,但我不知道如何将 ILogger 依赖项注入到我的类中。如果我使用 ASP.NET Core 5,这很容易,但我使用的是 .NET Core 控制台应用程序。我怎样才能做类似的事情?
public class TestStrategy
{
private static readonly ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType.Name);
...
}
Run Code Online (Sandbox Code Playgroud)
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
Run Code Online (Sandbox Code Playgroud)
我必须 DIlogger进入所有课程吗?
我正在使用 .NET 最小 API,并且遇到了枚举的 JSON 序列化/反序列化行为的问题。尽管我尝试更改使用字符串而不是整数的行为,但 Swashbuckle.AspNetCore 的 Swagger 文档仍然将枚举表示为整数。
using System.Text.Json.Serialization;
var builder = WebApplication.CreateBuilder(args);
// Docs: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis?view=aspnetcore-7.0#configure-json-deserialization-options-globally
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.MapPost("/api/v1/test", (TestRequest request) => Results.Ok(request));
app.Run();
public enum GridType
{
Arithmetic,
Geometric
}
public class TestRequest
{
public required string Name { get; init; }
public required GridType Type { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
但是当 Swagger UI 打开时,我仍然得到枚举的整数:
{
"name": "string",
"type": …Run Code Online (Sandbox Code Playgroud) 我有以下 ReactJS 项目结构,但出现以下错误:
./src/index.js
尝试导入错误:“./components”不包含默认导出(作为“App”导入)。
我的目标是导入这样的组件:(import { App, Navbar } from 'components';注意“组件”)而不是像./components/App,./components/App/index左右。为此,我需要在 components 目录中添加 index.js。我尝试通过以下代码执行此操作,但收到上述错误。
什么原因?我该如何解决?
有类似的线程,但我已经export default App;在 ./components/App/index.jsx 中导出它。也许原因是 .jsx 扩展名?
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './components';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
serviceWorker.unregister();
Run Code Online (Sandbox Code Playgroud)
export App from './App';
Run Code Online (Sandbox Code Playgroud)
import React, { Fragment } from 'react';
import './style.css';
import { BrowserRouter as Router, Switch, Route, Redirect } …Run Code Online (Sandbox Code Playgroud) 我读过一些文章,本地存储不是存储 JWT 令牌的首选方式,因为它不适合用于会话存储,因为您可以通过 JavaScript 代码轻松访问它,如果存在易受攻击的第三方,这可能会导致 XSS 本身-派对图书馆什么的。
从这些文章总结,正确的方法是使用 HttpOnly cookies 而不是本地存储来存储会话/敏感信息。
我找到了一项 cookie 服务,就像我当前用于本地存储的服务一样。我不清楚的是expires=Thu, 1 Jan 1990 12:00:00 UTC; path=/;`。它真的必须在某个时候过期吗?我只需要存储我的 JWT 和刷新令牌。全部信息都在那里。
import { Injectable } from '@angular/core';
/**
* Handles all business logic relating to setting and getting local storage items.
*/
@Injectable({
providedIn: 'root'
})
export class LocalStorageService {
setItem(key: string, value: any): void {
localStorage.setItem(key, JSON.stringify(value));
}
getItem<T>(key: string): T | null {
const item: string | null = localStorage.getItem(key);
return item !== null …Run Code Online (Sandbox Code Playgroud) TradingView 如何在策略测试器中计算它们的Run-Up和?Drawdown更具体地说,我正在寻找公式,因为我读了下面的文章,但没有得到公式部分。
该脚本运行良好,但就性能而言,它不会删除过去的行,这意味着当屏幕上出现大量新蜡烛时,它可能会崩溃。这就是我正在努力解决的问题。
\n如何让它只显示3行并删除旧的?类似于下面的内容,但我不知道具体如何实现。我知道我必须用数组来做到这一点,但不知道如何做。
\nnumberOfLines = 3\n\nvar label[] lbls = array.new_label()\nvar line[] lns = array.new_line()\n\nif array.size(lns) > 0\n for i = 0 to array.size(lns) - 1\n if i > numberOfLines\n line.delete(array.remove(lns, i))\nRun Code Online (Sandbox Code Playgroud)\n//@version=5\nindicator("RSI Market Structure display only 10", overlay = true, max_bars_back = 500, max_lines_count = 500, max_labels_count = 500)\n\n// \xe2\x80\x94\xe2\x80\x94\xe2\x80\x94\xe2\x80\x94\xe2\x80\x94\xe2\x80\x94\xe2\x80\x94\xe2\x80\x94\xe2\x80\x94\xe2\x80\x94\xe2\x80\x94\xe2\x80\x94\xe2\x80\x94\xe2\x80\x94\xe2\x80\x94\xe2\x80\x94\xe2\x80\x94\xe2\x80\x94\xe2\x80\x94\xe2\x80\x94 Constants {\n// \xe2\x80\x94\xe2\x80\x94\xe2\x80\x94\xe2\x80\x94\xe2\x80\x94 Colors\nvar color GREEN = color.green\nvar color RED = color.red\nvar color BLUE = color.blue\nvar color YELLOW = color.yellow\n\n// \xe2\x80\x94\xe2\x80\x94\xe2\x80\x94\xe2\x80\x94\xe2\x80\x94 Constants used in inputs\nvar string …Run Code Online (Sandbox Code Playgroud) 有一个库返回 aValueTask并且我有一个消耗 ValueTask 的同步方法。问题是有以下警告:
CA2012:ValueTask 实例不应直接访问其结果,除非该实例已完成。与任务不同,在 ValueTask 上调用 Result 或 GetAwaiter().GetResult() 不能保证在操作完成之前阻塞。如果您不能简单地等待实例,请考虑首先检查其 IsCompleted 属性(或者如果您知道情况如此,则断言它是 true)。
我如何解决它?
public void CreateListenKey()
{
var result = CreateSpotListenKeyAsync().GetAwaiter().GetResult(); // CA2012: ValueTask instances should not have their result directly accessed unless the instance has already completed. Unlike Tasks, calling Result or GetAwaiter().GetResult() on a ValueTask is not guaranteed to block until the operation completes. If you can't simply await the instance, consider first checking its IsCompleted property (or asserting it's true if you …Run Code Online (Sandbox Code Playgroud) c# ×6
asp.net-core ×4
.net ×2
hangfire ×2
pine-script ×2
.net-5 ×1
angular ×1
cookies ×1
javascript ×1
jsx ×1
jwt ×1
minimal-apis ×1
reactjs ×1
serilog ×1
swagger ×1
swashbuckle ×1
valuetask ×1