相关疑难解决方法(0)

结构和IDisposable

我想知道为什么不编译?

public static void Main(string[] args)
{
    using (MyStruct sss = new MyStruct())
    {

        sss.s = "fsdfd";// Cannot modify members of 'sss' because it is a 'using variable' 

        //sss.Set(12);    //but it's ok
    }
}

public struct MyStruct : IDisposable
{
    public int n;
    public string s;

    public void Set(int n)
    {
        this.n = n;
    }
    public void Dispose()
    {
        Console.WriteLine("dispose");
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:但它完美无缺.为什么?

public static void Main(string[] args)
        {

            using (MyClass sss = new MyClass())
            {
                sss.Field = "fsdfd"; …
Run Code Online (Sandbox Code Playgroud)

.net c# idisposable using

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

尝试阻止之前/之后的SemaphoreSlim.WaitAsync

我知道在同步世界中第一个片段是正确的,但是WaitAsync和async/await magic是什么?请给我一些.net内部.

await _semaphore.WaitAsync();
try
{
    // todo
}
finally
{
    _semaphore.Release();
}
Run Code Online (Sandbox Code Playgroud)

要么

try
{
    await _semaphore.WaitAsync();
    // todo
    }
    finally
    {
        _semaphore.Release();
    }
}
Run Code Online (Sandbox Code Playgroud)

.net c# semaphore locking async-await

7
推荐指数
4
解决办法
3826
查看次数

当一个struct是一个struct时,using语句是什么时候用它的参数?

我对以下代码有一些疑问:

using System;

namespace ConsoleApplication2
{
    public struct Disposable : IDisposable
    {
        public void Dispose() { }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (Test()) { }
        }

        static Disposable Test()
        {
            return new Disposable();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  • Disposable结构进行操作的using语句是否会从Test()结构框中返回?
  • 我怎样才能找到自己的答案?

为了试图找出自己,我检查了上面代码生成的IL,这里是Main(...)方法的IL :

.method private hidebysig static void Main(string[] args) cil managed
{
    .entrypoint
    .maxstack 1
    .locals init (
        [0] valuetype ConsoleApplication2.Disposable CS$3$0000)
    L_0000: call valuetype ConsoleApplication2.Disposable ConsoleApplication2.Program::Test()
    L_0005: stloc.0 
    L_0006: …
Run Code Online (Sandbox Code Playgroud)

c# struct boxing idisposable using

6
推荐指数
3
解决办法
1955
查看次数

标签 统计

c# ×3

.net ×2

idisposable ×2

using ×2

async-await ×1

boxing ×1

locking ×1

semaphore ×1

struct ×1