我有一段时间搞清楚如何处理来自ViewModel之外的类的Thread.
Thread来自一个Track类.这是以下ResponseEventHandler代码Track:
public delegate void ResponseEventHandler(AbstractResponse response);
public event ResponseEventHandler OnResponseEvent;
Run Code Online (Sandbox Code Playgroud)
当从我的Track对象中处理"命令"方法时,以下代码运行OnResponseEvent,它将线程中的消息发送回我的ViewModel:
if (OnResponseEvent != null)
{
OnResponseEvent(GetResponseFromCurrentBuffer());
}
Run Code Online (Sandbox Code Playgroud)
GetResponseFromCurrentBuffer()只返回一个消息类型,它是一个预定义的类型Track.
我的MainWindowViewModel构造函数创建了一个事件处理程序OnResponseEvent从Track:
public MainWindowViewModel()
{
Track _Track = new Track();
_Track.OnResponseEvent +=
new Track.ResponseEventHandler(UpdateTrackResponseWindow);
}
Run Code Online (Sandbox Code Playgroud)
所以,我的想法是每次有来自OnResponseEventThread的新消息时,我都会运行该UpdateTrackResponseWindow()方法.此方法将新的消息字符串附加到ObservableCollection<string>名为的列表属性TrackResponseMessage:
private void UpdateTrackResponseWindow(AbstractResponse message)
{
TrackResponseMessage.Add(FormatMessageResponseToString(message));
}
Run Code Online (Sandbox Code Playgroud)
该FormatMessageResponseToString()方法仅将消息与其中的所有预定义消息类型进行比较Track,并进行一些漂亮的字符串格式化.
主要问题是: 运行时UI消失TrackResponseMessage.Add().可执行文件仍在后台运行,结束任务的唯一方法是关闭Visual Studio …
当 TextBox 更改时,我需要调用一个方法,但TextBox.Caret不是 a DependencyProperty,因此无法绑定它。如何知道插入符位置何时发生变化?
我的 C# 应用程序使用控制台应用程序启动一个进程。
该进程正在正确启动并且在任务管理器中可见,但该进程在没有窗口的情况下运行。
如何使用自己的窗口运行控制台应用程序?
我的代码:
p_info.UseShellExecute = true;
p_info.CreateNoWindow = false;
p_info.WindowStyle = ProcessWindowStyle.Normal;
Process.Start(p_info);
Run Code Online (Sandbox Code Playgroud) 我在WPF项目中使用AvalonDock和MVVM.
当我点击"X"(选项卡的关闭按钮)时,我的文档关闭但保留在内存中.它似乎只是隐藏的.它不会从我的Model.Documents收藏中删除.
如果我添加DockingManager_DocumentClosing并尝试从集合中删除我的文档,我会在以下方法中收到异常,Xceed.Wpf.AvalonDock.Layout.LayoutContent因为它parentAsContainer是null.
/// <summary>
/// Close the content
/// </summary>
/// <remarks>Please note that usually the anchorable is only hidden (not closed). By default when user click the X button it only hides the content.</remarks>
public void Close()
{
var root = Root;
var parentAsContainer = Parent as ILayoutContainer;
parentAsContainer.RemoveChild(this);
if (root != null)
root.CollectGarbage();
OnClosed();
}
Run Code Online (Sandbox Code Playgroud)
有没有人知道如何管理AvalonDock中可以从我的文件中移除的文件,Model.Documents以便在我按下Close按钮时最终被处理掉?
供参考:这是我的AvalonDock的XAML:
<avalonDock:DockingManager
x:Name="DockingManager"
DocumentsSource="{Binding DocumentItems}"
ActiveContent="{Binding ActiveMainWindowViewModel,
Converter={StaticResource RestrictedClassConverter}, …Run Code Online (Sandbox Code Playgroud) 我有Window几个控件.其中一个是DataGrid.我想实现一些非默认的焦点遍历.即:
DataGrid 是一个整体,而不是每一行.DataGrid聚焦时,用户可以使用向上和向下键导航行.DataGridHyperlinkColumn.当用户点击Space或Enter键时,它会执行超链接.目前我有以下代码:
<DataGrid x:Name="DocumentTemplatesGrid"
Grid.Row="2"
ItemsSource="{Binding Source={StaticResource DocumentTemplatesView}}"
IsReadOnly="True"
AutoGenerateColumns="False"
SelectionUnit="FullRow"
SelectionMode="Single"
TabIndex="1"
IsTabStop="True">
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="IsTabStop" Value="False"/>
</Style>
</DataGrid.CellStyle>
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="IsTabStop" Value="False"/>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridHyperlinkColumn Header="Name"
Width="2*"
Binding="{Binding Name}"/>
<DataGridTextColumn Header="Description"
Width="5*"
Binding="{Binding Description}"/>
<DataGridTextColumn Header="Type"
Width="*"
Binding="{Binding Type}"/>
</DataGrid.Columns>
</DataGrid>
Run Code Online (Sandbox Code Playgroud)
不幸的是,它没有达到我的期望.请你解释一下如何实现这个目标?
我知道之前已经问过这个问题,但谷歌搜索后我得不到正确的答案.
我有这些代码行:
Task.Run(() => DoSomething())
.ContinueWith(t=>Log.Error(t,"Error"), TaskContinuationOptions.OnlyOnFaulted);
Task.Factory.StartNew(() => DoSomething())
.ContinueWith(t=>Log.Error(t,"Error"),TaskContinuationOptions.OnlyOnFaulted);
Run Code Online (Sandbox Code Playgroud)
成功运行后DoSomething,Task.Run投掷TaskCanceledException时Task.Factory.StartNew工作正常.为什么?
进一步阅读:
Stephen Clearly为什么不使用Task.Factory.StartNew
MSDN Link
更新2: 示例代码:
private async void button27_Click(object sender, EventArgs e)
{
var r = new Random(System.DateTime.Now.Millisecond);
await Task.Factory.StartNew(
() => {
Divide(r.Next(100), r.Next(-1, 10));
Log.Information("Divide Done!");
},
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default)
.ContinueWith(
t => {
Log.Error(t.Exception,"There is an exception on Divide");
},
TaskContinuationOptions.OnlyOnFaulted);
}
private static void Divide(int a, int b)
{
var c = a/b;
}
Run Code Online (Sandbox Code Playgroud) ASP.NET Core 结合 Identity 已经提供了一种在登录后检查角色的简单方法,但我想在每次控制器操作之前查询当前用户的当前角色的数据库。
我已经阅读了 Microsoft 提供的基于角色、基于策略和基于声明的授权。( https://docs.microsoft.com/en-us/aspnet/core/security/authorization/introduction ) 这些解决方案似乎都没有检查每个操作的角色。这是我以某种基于策略的授权的形式实现预期结果的最新尝试:
在 Startup.cs 中:
DatabaseContext context = new DatabaseContext();
services.AddAuthorization(options =>
{
options.AddPolicy("IsManager",
policy => policy.Requirements.Add(new IsManagerRequirement(context)));
options.AddPolicy("IsAdmin",
policy => policy.Requirements.Add(new IsAdminRequirement(context)));
});
Run Code Online (Sandbox Code Playgroud)
在我的需求文件中:
public class IsAdminRequirement : IAuthorizationRequirement
{
public IsAdminRequirement(DatabaseContext context)
{
_context = context;
}
public DatabaseContext _context { get; set; }
}
public class IsAdminHandler : AuthorizationHandler<IsAdminRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, IsAdminRequirement requirement)
{
// Enumerate all current users roles
int userId = Int32.Parse(context.User.Claims.FirstOrDefault(c …Run Code Online (Sandbox Code Playgroud) 我知道这个问题已经被问了不止一次,但是我不确定结果是否正确。该操作似乎太快了,所以我想仔细检查一下是否确实如此。
我有一个例程将一个字符串拆分为一个List<byte[]>。我想检查该操作所花费的时间,因此我将代码修改为如下所示:
// Deserializes base64 received from POST service
var str = JsonConvert.DeserializeObject<JsonText>(body).text;
Stopwatch stopWatch = Stopwatch.StartNew();
// parseText is a routine that splits str into
// byte[] of maximum size 100 and puts them into
// a List<byte[]> that is then returned
commands = DummyClass.parseText(str);
stopWatch.Stop();
TimeSpan timespan = stopWatch.Elapsed;
Console.WriteLine(timespan.TotalMilliseconds.ToString("0.0###"));
...
Run Code Online (Sandbox Code Playgroud)
我使用8000个字符串运行了例程,预计运行时间为几毫秒,但令人惊讶的是,整个操作的运行时间最多为0.8ms,这预计会慢很多。
我读取的测量值有误吗?0.8表示8ms吗?在测量时间时我做错什么了吗?
非常感谢你!
为什么SonarQube会抱怨这部分代码?
我检查了这段代码并不总是这个值是真的.
public static void WriteJson(object value)
{
decimal decimalValue = ((decimal?)value).Value;
int intValue = (int)decimalValue;
if (decimalValue == intValue)
Console.WriteLine(intValue);
else
Console.WriteLine(decimalValue);
Console.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)
为什么SonarQube抱怨这个?
我的 Npgsql 版本 3.2.5 - Postgresql 9.6
我收到此错误CommandType.StoredProcedure(但CommandType.Text有效):
Npgsql.PostgresException:'42883:函数 customer_select(pEmail => 文本,密码 => 文本) 不存在'
string sql3 = @"customer_select";
NpgsqlConnection pgcon = new NpgsqlConnection(pgconnectionstring);
pgcon.Open();
NpgsqlCommand pgcom = new NpgsqlCommand(sql3, pgcon);
pgcom.CommandType = CommandType.StoredProcedure;
pgcom.Parameters.AddWithValue(":pEmail", "myemail@hotmail.com");
pgcom.Parameters.AddWithValue(":pPassword", "eikaylie78");
NpgsqlDataReader pgreader = pgcom.ExecuteReader();
while (pgreader.Read()) {
string name = pgreader.GetString(1);
string surname = pgreader.GetString(2);
}
Run Code Online (Sandbox Code Playgroud)
这是数据库中的函数:
CREATE OR REPLACE FUNCTION public.customer_select(
pemail character varying, ppassword character varying)
RETURNS SETOF "CustomerTest"
LANGUAGE 'plpgsql'
COST 100.0
AS $function$
BEGIN …Run Code Online (Sandbox Code Playgroud)