C#7.0 –丢弃和IDisposableable输出参数 [英] C# 7.0 – Discards and IDisposable out argument

查看:57
本文介绍了C#7.0 –丢弃和IDisposableable输出参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

丢弃功能是否可以与IDisposable对象一起正常使用?

Is Discards feature correctly works with IDisposable objects?

在需要时是否调用 Dispose(); ?

我有一个代码:

Boolean existing = Mutex.TryOpenExisting(name: key, rights: MutexRights.ReadPermissions, result: out Mutex _);

这里我只需要现有的 变量值.

Here I need only existing variable value.

如您所见,我正在此处尝试使用"discard"变量,但不确定这种情况下的正确用法.

As you see, I'm trying to use "discard" variable here, but I'm not sure this is correct usage in this case or not.

因为互斥对象obj实现了IDisposable.

Because of Mutex obj implements IDisposable.

那么在这种情况下哪种方法是正确的?这个:

So which way will be correct in this case? this:

Boolean existing = Mutex.TryOpenExisting(name: key, rights: MutexRights.ReadPermissions, result: out Mutex _);

或者这个:

Mutex mutex; 
Boolean existing = Mutex.TryOpenExisting(name: key, rights: MutexRights.ReadPermissions, result: mutex);
mutex.Dispose();

推荐答案

我创建了一个测试应用程序来检查@CamilioTerevinto的答案.

I have created a test application to check @CamilioTerevinto answer.

一个简单的Winforms应用程序,具有以下方法:

A simple winforms app with a method:

public bool TestMethod(out Image bmp)
{
    Thread.Sleep(3000);

    bmp = Bitmap.FromFile(@"C:\Users\UKS\Desktop\2000x2000pixels.bmp");

    Thread.Sleep(1000);

    return true;
}

让我们尝试一个代码:

public Form1()
{
    InitializeComponent();
    Image img;
    var a = TestMethod(out img);
    img.Dispose();
}

我们看到了预期的行为-图像被处置,内存已释放.

We see an expected behavior -- image was disposed and memory was free.

让我们尝试下一个代码:

Let's try next code:

public Form1()
{
    InitializeComponent();
    var a = TestMethod(out _);
}

我们看到,图像没有被丢弃.内存不是免费的.

As we see, image wasn't disposed. Memory wasn't free.

让我们再尝试一些测试:

Let's try few more tests:

构造:

var a = TestMethod(out _.Dispose());

将无法正常工作.告诉您_在当前上下文中不存在.

Will not work. It's tell's that _ doesn't exist in current context.

构造:

var a = TestMethod(out _);
_.Dispose();

将会得到相同的结果.

所以......

这篇关于C#7.0 –丢弃和IDisposableable输出参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆