小编Reu*_*ass的帖子

如何获取当前任务参考?

如何引用我的代码在其中执行的任务?

ISomeInterface impl = new SomeImplementation();
Task.Factory.StartNew(() => impl.MethodFromSomeInterface(), new MyState());

...

void MethodFromSomeInterface()
{
    Task currentTask = Task.GetCurrentTask();    // No such method?
    MyState state = (MyState) currentTask.AsyncState();
}
Run Code Online (Sandbox Code Playgroud)

因为我正在调用一些接口方法,所以我不能只将新创建的任务作为附加参数传递.

c# task-parallel-library

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

我可以在RHV(右手值)中使用using语句吗?

我想using纯粹用于范围管理.我可以省略对实现的底层对象的显式引用IDisposable吗?

例如,给出这个声明:

class ITransactionScope : IDisposable {}
class TransactionGuard : ITransactionScope {...}

class DbContext
{
    public IDisposable ITransactionScope()
    {
        return new TransactionGuard();
    } 
}
Run Code Online (Sandbox Code Playgroud)

我可以做以下事情:

void main()
{
    var dbContext = new DbContext();

    using (dbContext.TransactionScope())
    {
        // the guard is not accessed here
    }
}
Run Code Online (Sandbox Code Playgroud)

声明中的TransactionGuard实例是否存活using

c#

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

强制泛型参数的类型是接口而不是特定类

鉴于这些接口和实现

interface IService {}
class Service : IService {}
Run Code Online (Sandbox Code Playgroud)

用通用方法

void Register<I>(I service)
{
    var type = typeof(I);
}
Run Code Online (Sandbox Code Playgroud)

如何使以下几行与泛型类型保持一致?

Register<IService>(new Service())    // type is 'IService'
Register(new Service());             // type is 'Service'
Run Code Online (Sandbox Code Playgroud)

有两种选择:

  • 这两行都是使用IServie类型编译的
  • 第二行无法编译

c# generics

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

标签 统计

c# ×3

generics ×1

task-parallel-library ×1