小编ila*_*sch的帖子

在类构造C#之后运行异步操作

我创建了一个锁对象包装器(类),它使用semaphoreSlim(1)作为我的管理器(类)操作的锁机制.
我的经理类包含一个锁,我在构造新的包装类时发送,然后我在这个包装类锁上使用Await(实际上等待我在构造时发送它的锁).并在Dispose上释放它(包装类的目的是自动锁定和释放,锁定构造,并在处置时释放).

我将这种模式用于我构建的新锁包装:

//_syncLock is a class that used as member lock to use in my operations as async lock.
using (OperationSyncLockWrapper syncLock = new OperationSyncLockWrapper(_syncLock))
{
    await syncLock.Wait(); //I wish to avoid this line and run it automatically
    await SomeAsyncOperation(parameter1);
}  
Run Code Online (Sandbox Code Playgroud)

因为我不能在构造函数方法中使用async/await.还有另一种方法可以等待我刚创建的新对象 - 在类构造上还是之后?

c# asynchronous async-await

0
推荐指数
1
解决办法
360
查看次数

从int成员C#返回Task <int>最佳实践

我班上有一个int类型的成员.
我想用一个返回该成员的Task函数公开该类.

int _someMember;
Run Code Online (Sandbox Code Playgroud)

我知道我能做到:

public int ReturnTheMember() { return _someMember; }
Run Code Online (Sandbox Code Playgroud)

但是我所有的类功能必须是基于任务的.

是否可以将此调用包装在任务中?就像是:

    public async Task<int> ReturnTheMember()
    {
        await Task.FromResult(0);
        return _someMember;
    }
Run Code Online (Sandbox Code Playgroud)

注意 - 我必须执行Task.FromResult(0)因为我将警告视为错误 - 这不会编译,因为签名上的async方法必须包含"await".

我想知道这是否是我用过的好模式.或者这样做是错误的.

c# async-await

0
推荐指数
1
解决办法
820
查看次数

C#返回int并返回后增加值

我有一个属性,接收一个int,每个获取数字将返回int,然后我需要增加int一个.
如果我喜欢这样:

    public int Number
    {
        set;
        get
        {
            Number++;
            return Number;
        }
    }
Run Code Online (Sandbox Code Playgroud)

它不好,因为如果我从7000开始,它将从7001开始.
如何在返回后增加?

我可以用return Number++;吗?

c# properties

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

访问using语句的对象

我创建了一个using()而没有指定对象名.
我的问题是如何访问我的新对象并打印其名称?

class Program
{
    static void Main(string[] args)
    {
        AnimalFactory factory = new AnimalFactory();
        using (factory.CreateAnimal())
        {
            Console.WriteLine("Animal {} created inside a using statement !");
            //How can i print the name of my animal ?? something like this.Name  ?
        }
        Console.WriteLine("Is the animal still alive ?");

    }
}

public class AnimalFactory
{ 
    public IAnimal CreateAnimal()
    {
        return new Animal();
    }
}

public class Animal : IAnimal
{
    public string Name { get; set; }

    public Animal()
    {
        Name = …
Run Code Online (Sandbox Code Playgroud)

.net c#

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

标签 统计

c# ×4

async-await ×2

.net ×1

asynchronous ×1

properties ×1