小编Seb*_*ann的帖子

使用IronPython时,禁用第一次机会异常但调试器在try ... catch中停止

应该在不停止调试器的情况下执行以下代码:

var engine = Python.CreateEngine(AppDomain.CurrentDomain);
var source = engine.CreateScriptSourceFromString("Foo.Do()");
var compiledCode = source.Compile(new PythonCompilerOptions { Optimized = true });

try
{
    compiledCode.Execute(
         engine.CreateScope(
            new Dictionary<string, object> { 
                                            { "Foo", new Foo() }
                                           }));

    MessageBox.Show("Executed without error");
}
catch (Exception ex)
{
    MessageBox.Show(string.Format("Error at execution: {0}", ex.Message));
}
Run Code Online (Sandbox Code Playgroud)

使用这个类:

public class Foo
{
    public void Do()
    {
        throw new InvalidOperationException("The debugger should not break here...");
    }
}
Run Code Online (Sandbox Code Playgroud)

脚本执行在try-block中运行以处理任何异常.如果我有像1 / 0所有作品perfekt的代码.异常是在Python(或引擎)中创建的,我的catch块按预期调用,而不强制调试器在任何地方停止.

调用try { new Foo().Do(); } catch {}C#也可以在不停止调试器的情况下工作. …

c# ironpython exception first-chance-exception

14
推荐指数
1
解决办法
311
查看次数

WeakEventManager <TEventSource,TEventArgs>和PropertyChangedEventManager导致内存泄漏

我有一个应用程序,我无法删除事件处理程序,因为我不知道何时将释放最后一个引用.

我的应用程序包含一个PropertyChanged事件源,它被放入一个也实现的容器类中INotifyPropertyChanged.此层次结构包含6个以上的级别.可以将级别的每个实例放置到多个其他实例中.这就是为什么我无法确定何时释放这些实例的原因.

最低级别的实例将适用于整个应用程序运行时.这导致所有其他实例都不会被释放,我得到了内存泄漏.

为了避免这个事件驱动的内存泄漏我试图使用WeakEventManager(TEventSource, TEventArgs).此类仅在.Net 4.5中可用,并且由于与现有硬件的兼容性,我将使用.Net 4.0.

在.Net 4.0中PropertyChangedEventManager可以使用相同的功能INotifyPropertyChanged.

我的课程正确释放.

但是仍然存在内存泄漏.

我将我的应用程序简化为以下产生内存泄漏的代码:

// This code will force the memory leak
while (true)
{
    var eventSource = new StateChangedEventSource();
    var eventReceiver = new StateChangedEventReceiver();

    PropertyChangedEventManager.AddListener(eventSource, eventReceiver, string.Empty);
}

public class EventSource : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
}

public class  EventReceiver : IWeakEventListener
{
    public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
    {
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

是的,我知道没有RemoveListener电话.我无法确定何时从未使用过实例并且可以释放它.如果我知道我可以使用正常的事件注册和注销.在那种情况下,我不必使用 …

.net c# events memory-leaks event-handling

6
推荐指数
2
解决办法
5887
查看次数

如何在没有竞争条件和异常的情况下检测BlockingCollection的AddingCompleted?

我使用的BlockingCollection{T}是仅由一个线程填充且仅由一个线程消耗的线程。生产和消费物品运行良好。问题出在这个操作的最后。任务在 处阻塞(如预期)GetConsumingEnumerableCompleteAdding调用任务后将处理BlockingCollection并完成,没有任何异常。到目前为止,一切都很好。

现在我有一个线程将项目添加到BlockingCollection. 该线程必须进行测试IsAddingCompleted,然后必须添加该项目。IsAddingCompleted但请求和添加项目之间存在竞争条件。有一个TryAdd- 方法,但如果添加已经完成,也会引发异常。

如何在没有额外锁定的情况下添加已完成的项目或测试?为什么会TryAdd抛出异常?如果添加已经完成,返回false即可。

非常简化的代码如下所示:

private BlockingCollection<string> _items = new BlockingCollection<string>();

public void Start()
{
    Task.Factory.StartNew(
        () =>
            {
                foreach (var item in this._items.GetConsumingEnumerable())
                {
                }

                this._items.Dispose();
            });

    Thread.Sleep(50); // Wait for Task

    this._items.CompleteAdding(); // Complete adding
}

public void ConsumeItem(string item)
{
    if (!this._items.IsAddingCompleted)
    {
        this._items.Add(item);
    }
}
Run Code Online (Sandbox Code Playgroud)

是的,我知道这段代码没有意义,因为几乎没有机会添加任何项目,并且 foreach 循环没有注意到。消耗任务对我的问题来说并不重要。

问题如ConsumeItem-method 所示。我可以添加一个额外的锁(信号量)ConsumeItem和 …

c# multithreading race-condition blockingcollection

6
推荐指数
0
解决办法
756
查看次数

WinForms 应用程序中的异步任务 Main() 具有异步初始化

我们有一个使用异步初始化过程的 winforms 应用程序。简单地说,应用程序将运行以下步骤:

  • Init - 这运行异步
  • 显示主窗体
  • 应用程序.运行()

当前现有的和工作的代码如下所示:

[STAThread]
private static void Main()
{
    SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());

    var task = StartUp();
    HandleException(task);

    Application.Run();
}

private static async Task StartUp()
{
    await InitAsync();

    var frm = new Form();
    frm.Closed += (_, __) => Application.ExitThread();
    frm.Show();
}

private static async Task InitAsync()
{
    // the real content doesn't matter
    await Task.Delay(1000);
}

private static async void HandleException(Task task)
{
    try
    {
        await Task.Yield();
        await task;
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        Application.ExitThread(); …
Run Code Online (Sandbox Code Playgroud)

program-entry-point winforms async-await c#-7.1

6
推荐指数
1
解决办法
4077
查看次数

应该何时处理ManualResetEvent?

我正在使用一个使用ManualResetEvent同步线程的应用程序.FxCop告诉我处理这些物品.我发现以下讨论告诉了我同样的事情:

我需要Dispose()或Close()一个EventWaitHandle吗?

但我不知道何时处理ManualResetEvent的实例.

以下简化代码演示了此问题:

private void btn_Click(object sender, EventArgs e)
{
    var mre = new ManualResetEvent(false);
    new Thread(() => this.SetEvent(mre)).Start();
    for (int i = 0; i < 10; ++i)
    {
        new Thread(() => this.WaitFor(mre)).Start();
    }
}

private void SetEvent(ManualResetEvent manualResetEvent)
{
    Thread.Sleep(10000);
    manualResetEvent.Set();
}

private void WaitFor(ManualResetEvent manualResetEvent)
{
    manualResetEvent.WaitOne();
}
Run Code Online (Sandbox Code Playgroud)

问题是存在多个ManualResetEvent实例,并且多个线程正在等待每个实例.

如果我记住列表中的实例,我不知道何时处理它.在WaitOne()之后处理它 - 调用将多次处理它,并且可能在其他线程仍在等待时处理它.

创建事件的线程没有任何对它的引用.setter-thread不应该处置它,因为还有其他线程在等待这个MRE.每个等待的线程都无法像前面提到的那样处理它.

所以问题是:什么时候应该处理这个ManualResetEvent?

.net c# multithreading idisposable manualresetevent

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

C#.Net 4.0 mscorlib包含ReadOnlyDictionary?

我需要一个ReadOnlyDictionary.所有帖子告诉我,.Net 4.0中没有.出于这个原因,我创建了自己的实现.

在做完Resharper 5.1后告诉我一个模糊的引用,System.Collections.ObjectsModel.ReadOnlyDictionary但代码编译没有错误.

我试图使用此实现,但它无法访问.为什么?

我编写了以下代码来测试ReadOnlyDictionary.Net 4.0中是否存在:

var foo = from assembly in AppDomain.CurrentDomain.GetAssemblies()
          where assembly.FullName.Contains("mscorlib")
          from type in assembly.GetTypes()
          where type.Name.StartsWith("ReadOnly")
          select type.FullName + " " + assembly.FullName;
Run Code Online (Sandbox Code Playgroud)

令人惊讶的结果是:

System.Collections.ReadOnlyCollectionBase mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Collections.ObjectModel.ReadOnlyCollection`1 mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Collections.ObjectModel.ReadOnlyDictionary`2 mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Collections.ObjectModel.ReadOnlyDictionaryHelpers mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Runtime.InteropServices.WindowsRuntime.ReadOnlyArrayAttribute mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Runtime.InteropServices.WindowsRuntime.ReadOnlyDictionaryKeyCollection`2 mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Runtime.InteropServices.WindowsRuntime.ReadOnlyDictionaryKeyEnumerator`2 mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Runtime.InteropServices.WindowsRuntime.ReadOnlyDictionaryValueCollection`2 mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Runtime.InteropServices.WindowsRuntime.ReadOnlyDictionaryValueEnumerator`2 mscorlib, Version=4.0.0.0, Culture=neutral, …
Run Code Online (Sandbox Code Playgroud)

.net c# mscorlib resharper-5.0

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

没有错误的条件匹配强制匹配?

我在 c# 中使用以下正则表达式来匹配一些输入案例:

^
(?<entry>[#])?
(?(entry)(?<id>\w+))
(?<value>.*)
$
Run Code Online (Sandbox Code Playgroud)

这些选项忽略了模式空格。

我的输入如下所示:

hello
#world
[xxx]
Run Code Online (Sandbox Code Playgroud)

这一切都可以在这里测试:DEMO

我的问题是这个正则表达式与最后一行不匹配。为什么?我要做的是检查输入字符。如果它在那里,我会通过\w+. 其余的输入应在最后一组中捕获。

这是一个简单的正则表达式和简单的输入。

如果我将 id 正则表达式更改为类似(?(entry)(?<id>\w+)|),(?(entry)(?<id>\w+))?(?(entry)(?<id>\w+)?).

我试图理解为什么条件组与原始正则表达式中所述不匹配。

我对正则表达式很熟悉,并且知道正则表达式可以简单地^(\#(?<id>\w+))?(?<value>.*)$满足我的需求。但真正的正则表达式包含另外两个可选组:

^
(?<entry>[#])?
(\?\:)?
(\(\?(?:\w+(?:-\w+)?|-\w+)\))?
(?(entry)(?<id>\w+))
(?<value>.*)
$
Run Code Online (Sandbox Code Playgroud)

这就是我尝试使用条件匹配的原因。

更新 10/12/2018

我测试了一下。我发现以下正则表达式应该匹配每个输入,甚至是空输入 - 但它没有:

(?(a)a).*
Run Code Online (Sandbox Code Playgroud)

演示

我认为这是 .net regex 中的一个错误并将其报告给 microsoft:有关更多信息,请参见此处

c# regex

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

StackOverflowException使用具有协变泛型参数的explict接口实现

我正在IClonable使用协变泛型参数扩展现有接口.

public interface ICloneable<out T> : ICloneable
{
    new T Clone();
}
Run Code Online (Sandbox Code Playgroud)

现在我在基类中实现了这个接口.

public class Base : ICloneable<Base>
{
    public string StrValue { get; set; }

    Base ICloneable<Base>.Clone()
    {
        var result = (Base)FormatterServices.GetUninitializedObject(this.GetType());
        result.StrValue = this.StrValue;
        return result;
    }

    public virtual object Clone()
    {
        return ((ICloneable<Base>)this).Clone();
    }
}
Run Code Online (Sandbox Code Playgroud)

调用Clone()按预期工作,并返回具有相同值的基类的新实例.

我创建了一个派生类,BaseICloneable<T>再次实现了接口以返回这个新类型:

public class Sub : Base, ICloneable<Sub>
{
    public int IntValue { get; set; }

    Sub ICloneable<Sub>.Clone()
    {
        var result = (Sub)base.Clone();
        result.IntValue …
Run Code Online (Sandbox Code Playgroud)

c# generics inheritance covariance

3
推荐指数
1
解决办法
114
查看次数