C#7.0 –丢弃和IDisposableable输出参数

编程入门 行业动态 更新时间:2024-10-28 08:21:09
本文介绍了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输出参数

本文发布于:2023-11-04 10:40:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557694.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   IDisposableable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!