小编Que*_*ire的帖子

C#编译器如何知道何时切断异步方法?

我正在尝试更多地了解async/await,特别是编译器如何知道"暂停"某个async方法并且await不会产生额外的线程.

举个例子,假设我有一个async类似的方法

DoSomeStuff();
await sqlConnection.OpenAsync();
DoSomeOtherStuff();
Run Code Online (Sandbox Code Playgroud)

我知道这await sqlConnection.OpenAsync();是我的方法被"挂起"的地方,并且调用它的线程返回到线程池,一旦Task跟踪连接打开完成,就会发现可用的线程运行DoSomeOtherStuff().

| DoSomeStuff() | "start" opening connection | ------------------------------------ | 
| ---------------------------------------------------------- | DoSomeOtherStuff() - |
Run Code Online (Sandbox Code Playgroud)

这是我感到困惑的地方.我查看OpenAsync(https://referencesource.microsoft.com/#System.Data/System/Data/Common/DBConnection.cs,e9166ee1c5d11996,references)的源代码,它是

    public Task OpenAsync() {
        return OpenAsync(CancellationToken.None);
    }

    public virtual Task OpenAsync(CancellationToken cancellationToken) {
        TaskCompletionSource<object> taskCompletionSource = new TaskCompletionSource<object>();

        if (cancellationToken.IsCancellationRequested) {
            taskCompletionSource.SetCanceled();
        }
        else {
            try {
                Open();
                taskCompletionSource.SetResult(null);
            }
            catch (Exception e) {
                taskCompletionSource.SetException(e);
            }
        }

        return …
Run Code Online (Sandbox Code Playgroud)

.net c# asynchronous async-await

5
推荐指数
2
解决办法
136
查看次数

为什么我的扩展方法不起作用?

我有一个扩展方法

public static class DbMigratorExtensions
{
    public static IEnumerable<string> DoCoolStuff(this DbMigrator dbMigrator, string[] first, string[] second)
    {
        // ... 
    }
}
Run Code Online (Sandbox Code Playgroud)

而我正试着用它

DbMigrator.DoCoolStuff
Run Code Online (Sandbox Code Playgroud)

但我得到了

'DbMigrator' does not contain a definition for ...
Run Code Online (Sandbox Code Playgroud)

我已经遵循了所有的要点

为什么我的扩展方法没有出现在我的测试类中?

另外我会注意到VS认可

DbMigratorExtensions.DoCoolStuff
Run Code Online (Sandbox Code Playgroud)

所以我不确定为什么它不能作为扩展方法.

.net c# entity-framework

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

.NET有办法在边界之间对列表进行排序吗?

简单的问题,所以如果我不需要,我不必重新发明轮子.

.NET是否有等效的方法

// sorts a list in-place between bounds [a, b)
public static void SortBounds<T>(this List<T> list, int a, int b)
{
    // ... 
}
Run Code Online (Sandbox Code Playgroud)

(可能带有可选的谓词)?

例:

var list = {1, 5, 3, 1, 9, 2, 4 }
list.SortBounds(0, 4);
// now list is {1, 1, 3, 5, 2, 4 }
Run Code Online (Sandbox Code Playgroud)

.net c# sorting algorithm

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