小编Moo*_*ght的帖子

如何在 C# 中正确地多线程调用在运行时调用的 DLL

全部,

我希望编写一个插件 .dll 以供在运行时调用的 .NET 应用程序使用/调用。我的 .dll 是一个 WinForm 并显示正在执行的(计算成本高的)操作。从主应用程序调用的 .dll 是通过 .NET 调用的System.Reflection。我必须向调用应用程序提供NameSpaceClass和我想要调用的方法

我想对我的 .dll 进行多线程处理,以便它对 UI 更加友好,而且我只对BackgroundWorkers非常熟悉。

编辑:问题的扩展。

所以,我调用 .dll 如下:

if (classType != null)
{
    if (bDllIsWinForm)
    {
        classInst = Activator.CreateInstance(classType);
        Form dllWinForm = (Form)classInst;
        dllWinForm.Show();

        // Invoke required method.
        MethodInfo methodInfo = classType.GetMethod(strMethodName);
        if (methodInfo != null)
        {
            object result = null;
            // The method being called in this example is 'XmlExport'.
            result = methodInfo.Invoke(classInst, new …
Run Code Online (Sandbox Code Playgroud)

c# dll multithreading winforms

5
推荐指数
1
解决办法
7282
查看次数

在WinForm上停止触发输入键

我有一个基本的自定义对话框,用于WinForms应用程序中的各种控件.该对话框如下所示:

自定义对话框

由于各种原因,我不希望用户能够使用Enter密钥来选择"是"选项(buttonYes).以前我确实想要这种行为,并相应地设置AcceptButton了Yes按钮(buttonYes)的属性.我有scince删除了这个,将buttonYes's AcceptButton属性设置为'None',但是buttonYes.ClickEnter按下该键时,表单仍会触发该事件.我也尝试处理KeyPressKeyDown事件,但Enter使用密钥时不会触发这些事件.这是基本和恼人的,有没有人遇到过这个,我该怎么做才能实现我想要的功能?

c# dialog winforms

5
推荐指数
2
解决办法
1万
查看次数

TPL如何进行'回叫'

我有一个小应用程序,需要测试多个连接的SQL连接字符串(每个连接一次完成).要做到这一点,我ConnectionTimeout = 5暂时设置为避免漫长的等待,如果连接无效和ConnectionTimeout = 0(等待永远),比如说.

为了避免在我们尝试Open()连接错误时挂起UI (即使ConnectionTimeout = 5等待时间SqlException可能长达20秒),我想使用任务并行库(TPL)在单独的线程上运行测试.所以我剥离了我的新线程,如:

Task<bool> asyncTestConn = Task.Factory.StartNew<bool>
    (() => TestConnection(conn, bShowErrMsg));
return asyncTestConn.Result;
Run Code Online (Sandbox Code Playgroud)

问题是这仍然是锁定UI(显然),因为它在返回调用者之前等待结果.如何让代码返回控制到UI(腾出GUI),而从异步获取最终的结果Task

另外,Task我可以从合法的范围内做到MessageBox.Show("Some message")吗?这不起作用BackgroundWorkers,默认情况下,此池化线程是后台线程; 但它似乎不是一个问题.谢谢你的时间.

c# multithreading callback task-parallel-library

5
推荐指数
2
解决办法
3351
查看次数

TreeView 不显示 ImageList 中的图像

我有一个TreeView显示CheckBoxes:

在此处输入图片说明

我想检查给定目录是否包含“.mdf”数据库,如果包含,请检查它是否附加在所选服务器实例上。如果附加了数据库,我会针对该节点显示一张图像,如果未附加,则显示不同的图像。注:图片为 .png 格式,大小为 32x32...

我填充一个ImageList来自Properties.Resources

mainImageList = new ImageList();
mainImageList.Images.Add(Properties.Resources.Database);
mainImageList.Images.Add(Properties.Resources.DatabaseGrey);
Run Code Online (Sandbox Code Playgroud)

然后我遍历树并添加相关图像

public static void RecursiveAddImage(TreeNode treeNode, List<string> attachedList)
{
    if (String.Compare(Path.GetExtension(treeNode.Text), ".mdf", true) == 0)
    {
        string databaseName = treeNode.Text.Replace(".mdf", String.Empty);
        if (attachedList.Contains(databaseName))
        {
            treeNode.ImageIndex = 0;
            treeNode.SelectedImageIndex = 0;
        }
        else
        {
            treeNode.ImageIndex = 1;
            treeNode.SelectedImageIndex = 1;
        }
    }
    foreach (TreeNode node in treeNode.Nodes)
        RecursiveAddImage(node, attachedList);
}
Run Code Online (Sandbox Code Playgroud)

上面的代码毫无怨言地通过循环,找到“.mdf”并似乎添加了相关ImageIndexes但这些没有显示在.mdf 文件中TreeView。我在这里做错了什么,我可以ImageList在设计时添加(我似乎也做不到)?

我已经阅读了几篇文章,当然还有MSDN 文档,但我似乎仍然无法让它工作。一如既往的任何帮助,非常感谢。

c# treeview winforms

5
推荐指数
1
解决办法
5233
查看次数

定义通用方法

全部,我有一个方法,目前用于调用返回类型的DLL bool,这很好用.这个方法是

public static bool InvokeDLL(string strDllName, string strNameSpace, 
                             string strClassName, string strMethodName, 
                             ref object[] parameters, 
                             ref string strInformation, 
                             bool bWarnings = false)
{
    try
    {
        // Check if user has access to requested .dll.
        if (!File.Exists(Path.GetFullPath(strDllName)))
        {
            strInformation = String.Format("Cannot locate file '{0}'!",
                                           Path.GetFullPath(strDllName));
            return false;
        }
        else
        {
            // Execute the method from the requested .dll using reflection.
            Assembly DLL = Assembly.LoadFrom(Path.GetFullPath(strDllName));
            Type classType = DLL.GetType(String.Format("{0}.{1}", 
                                         strNameSpace, strClassName));
            if (classType != null)
            {
                object classInstance = Activator.CreateInstance(classType); …
Run Code Online (Sandbox Code Playgroud)

c# generics

5
推荐指数
1
解决办法
471
查看次数

覆盖WinForms MessageBox控件

总而言之,我理解对于广泛定制的对话框,我需要创建自己的表单和ShowDialog().但是,在我目前的情况下,我只想扩展MessageBox类,以便CustomMessageBox能够显示由系统确定的不同图标.

我之前没有覆盖过这样的控制,我甚至不知道从哪里开始.有人能指出我正确的方向吗?

谢谢你的时间.

c# overriding dialog winforms

5
推荐指数
1
解决办法
3398
查看次数

奇怪的 XAML 错误:“无法应用“System.Windows.StaticResourceExtension””

我有以下 XAML 来提供最近的文档菜单,例如 VS2012 的“文件”>“最近的文档”菜单

<MenuItem Header="_FILE">
    ...
    <MenuItem Header="_Recent Studies" 
              ItemsSource="{Binding RecentFiles}" 
              AlternationCount="{Binding RecentFiles.Count}" 
              HeaderTemplate="{x:Null}">
        <MenuItem.Resources>
            <Style TargetType="{x:Type MenuItem}" 
                   BasedOn="{StaticResource {x:Type MenuItem}}">
                <Setter Property="HeaderTemplate" >
                   <Setter.Value>
                      <DataTemplate>
                         <TextBlock>
                            <TextBlock.Text>
                               <MultiBinding StringFormat="{}{0}. {1}">
                                  <Binding Path="(ItemsControl.AlternationIndex)" 
                                           RelativeSource="{RelativeSource FindAncestor, 
                                                                           AncestorType={x:Type MenuItem}}"/>
                                  <Binding Path="FullFileName"/>
                               </MultiBinding>
                            </TextBlock.Text>
                         </TextBlock>
                      </DataTemplate>
                   </Setter.Value>
                </Setter>
            </Style>
        </MenuItem.Resources>
    </MenuItem>
    <Separator/>
        <MenuItem Header="E_xit" 
                  Height="22"
                  Icon="{Binding Source={StaticResource Close}, 
                                 Converter={StaticResource drawingBrushToImageConverter}}"
                  Command="{Binding ExitCommand}" />
</MenuItem>
Run Code Online (Sandbox Code Playgroud)

这有效!但是,我的 FILEMenuItem块的所有 XAML 都被突出显示,并且我收到编译时错误(代码运行并正常工作!),说

“System.Windows.StaticResourceExtension”类型的对象不能应用于需要“System.Windows.Style”类型的属性。

我使用的是.NET4.5和VS2012。为什么会发生这种情况?我该如何解决?

谢谢你的时间。

c# wpf menuitem .net-4.5 visual-studio-2012

5
推荐指数
1
解决办法
2908
查看次数

如何从另一个控件中绑定到自定义控件按钮可见性

我有一个自定义控件,它有一个按钮:

<UserControl x:Class="Gambit.Views.FileSelectionControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    SnapsToDevicePixels="True" 
    mc:Ignorable="d">
    ...
    <Button Content="Load" 
            Margin="5,5,5,5" 
            Height="22" 
            Width="70" 
            IsDefault="True" 
            IsEnabled="{Binding SelectedFileExists}" 
            AttachedCommand:CommandBehavior.Event="Click" 
            AttachedCommand:CommandBehavior.Command="{Binding CloseDialogCommand}"/>
    ...
</UserControl>
Run Code Online (Sandbox Code Playgroud)

我希望在另一个控件中包含此控件,但我想Load在主机控件中设置按钮的可见性; 就像是

<UserControl x:Class="Gambit.Views.SomeOtherControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    SnapsToDevicePixels="True" 
    mc:Ignorable="d">
    ...
    <GroupBox Header="Select Test Data">
        <Views:FileSelectionControl <Here Set the Load Button Visibility>/>
    </GroupBox>
    ...
</UserControl>
Run Code Online (Sandbox Code Playgroud)

在哪里<Here Set the Load Button Visibility>显示我想设置控件的可见性.如何完成[不破坏MVVM模式]?

谢谢你的时间.

c# wpf mvvm

5
推荐指数
1
解决办法
1188
查看次数

使用Moq模拟使用可选参数的方法

我有一个具有以下界面的消息框服务

public interface IMessageBoxService
{
    DialogResult DisplayMessage(IWin32Window owner, string text,
        string caption, MessageBoxButtons buttons, MessageBoxIcon icon,
        MessageBoxDefaultButton defaultButton = MessageBoxDefaultButton.Button1);
}
Run Code Online (Sandbox Code Playgroud)

它实际上包装了System.Windows.Forms消息框,并允许我模拟显示消息框的代码部分。现在,我有一个用于文本文档的搜索服务,如果搜索循环,该服务将显示“不再定位”消息。我想写这个类的功能的单元测试,将FindNextMethod

public TextRange FindNext(IDocumentManager documentManager, IMessageBoxService messageBoxService, 
        TextEditorControl textEditor, SearchOptions options, FindAllResultSet findAllResults = null)
{
    ...
    if (options.SearchType == SearchType.CurrentDocument)
    {
        Helpers.SelectResult(textEditor, range);
        if (persistLastSearchLooped)
        {
            string message = MessageStrings.TextEditor_NoMoreOccurrances;
            messageBoxService.DisplayMessage(textEditor.Parent, message,
                Constants.Trademark, MessageBoxButtons.OK, MessageBoxIcon.Information); <- Throws here.
            Log.Trace($"TextEditorSearchProvider.FindNext(): {message}");
            lastSearchLooped = false;
        }
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

我的测试是

[TestMethod]
public void FindInCurrentForwards()
{
    // …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing moq

5
推荐指数
1
解决办法
2124
查看次数

构建 ASP.NET Core 和 C++ 二进制文件的 Dockerfile

我需要构建一个 ASP.NET Core 应用程序,它调用 C++ 可执行文件来完成一些工作。我有 docker 文件可以为 .NET Core 和 C++ 构建两个图像,但它们单独运行

ASP.NET Core Dockerfile 如下所示:

FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
WORKDIR /app
EXPOSE 4444
EXPOSE 5599
ENV ASPNETCORE_URLS=https://+:4444;https://+:5599

# Creates a non-root user with an explicit UID and adds permission to access the /app folder
# For more info, please refer to https://aka.ms/vscode-docker-dotnet-configure-containers
# RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app
# USER appuser

FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /src

COPY …
Run Code Online (Sandbox Code Playgroud)

c++ linux docker asp.net-core ubuntu-16.04

5
推荐指数
1
解决办法
111
查看次数