如何正确使方法异步?

Ilu*_*tar 2 c# asynchronous async-await

我有计算Levenshtein距离的方法

public static LevenshteinMatches LevenshteinSingleThread(this string str, string expression, int maxDistance) {
        if (str.Length > expression.Length + 1) {
            int len = expression.Length;
            long strLen = str.Length - len + 1;
            int[] results = new int[strLen];
            int[][,] dimension = new int[strLen][,];
            for (int i = 0; i < strLen; i++) {
                dimension[i] = new int[len + 1, len + 1];
            }

            string source = str;
            source = source.ToUpper();
            expression = expression.ToUpper();

            for (int i = 0; i < strLen; i++) {
                results[i] = SqueareLevenshtein(ref dimension[i], str.Substring(i, len).ToUpper(), expression, len);
            }

            LevenshteinMatches matches = new LevenshteinMatches();

            for (int i = 0; i < strLen; i++) {
                if (results[i] <= maxDistance) {
                    matches.addMatch(str.Substring(i, len), Math.Round((1.0 - ((double)results[i] / len)) * 100.0, 2), i, len, results[i]);
                }
            }

            return matches;
        }
        else {
            LevenshteinMatch match = str.LevenshteinCPU(expression, maxDistance);
            if (match != null)
                return new LevenshteinMatches(match);
            else
                return new LevenshteinMatches();
        }
    }
Run Code Online (Sandbox Code Playgroud)

我应该怎么做才能使它异步?

或者我应该离开这种方法,只是以不同的方式调用它?

这是我试图让它异步; 不知道出了什么问题,但我无法得到任何结果 - 线程工作正常,但它只需要几毫秒.

public static async Task<LevenshteinMatches> LevenshteinSingleThread(this string str, string expression, int maxDistance) {
        return await Task.Factory.StartNew(() => {
            if (str.Length > expression.Length + 1) {
                int len = expression.Length;
                long strLen = str.Length - len + 1;
                int[] results = new int[strLen];
                int[][,] dimension = new int[strLen][,];
                for (int i = 0; i < strLen; i++) {
                    dimension[i] = new int[len + 1, len + 1];
                }

                string source = str;
                source = source.ToUpper();
                expression = expression.ToUpper();

                for (int i = 0; i < strLen; i++) {
                    results[i] = SqueareLevenshtein(ref dimension[i], str.Substring(i, len).ToUpper(), expression, len);
                }

                LevenshteinMatches matches = new LevenshteinMatches();

                for (int i = 0; i < strLen; i++) {
                    if (results[i] <= maxDistance) {
                        matches.addMatch(str.Substring(i, len), Math.Round((1.0 - ((double)results[i] / len)) * 100.0, 2), i, len, results[i]);
                    }
                }

                return matches;
            }
            else {
                LevenshteinMatch match = str.LevenshteinCPU(expression, maxDistance);
                if (match != null)
                    return new LevenshteinMatches(match);
                else
                    return new LevenshteinMatches();
            }
        });
    }
Run Code Online (Sandbox Code Playgroud)

其余的代码链接

这就是我所说的:

string s = "xcjavxzcbvmrmummuuutmtumuumtryumtryumtrutryumtryumtrymutryumtyumtryumtrmutyumtrurtmutymurtmyutrymut";

        s = string.Concat(Enumerable.Repeat(s, 4000));

        var watch = System.Diagnostics.Stopwatch.StartNew();
        var ret = s.LevenshteinSingleThread("jas", 1);
        var res = ret.Result;
        watch.Stop();



        var elapsedMs = watch.ElapsedMilliseconds;
Run Code Online (Sandbox Code Playgroud)

Sco*_*ain 5

你的函数没有任何异步,它完全是CPU绑定的工作.将签名更改为async Task<LevenshteinMatches>并且从不await在函数中使用应该在编译器中引起警告.

如果您真正追求的是使其并行工作,那么只需并行调用代码,而不是"使其异步".

string s = "xcjavxzcbvmrmummuuutmtumuumtryumtryumtrutryumtryumtrymutryumtyumtryumtrmutyumtrurtmutymurtmyutrymut";
s = string.Concat(Enumerable.Repeat(s, 4000));

var expressions = new[] {"jas", "cbv"}

var tasks = new List<Task<LevenshteinMatches>>()
foreach(var expression in expressions)
{
   var task = new Task.Run(()=> message.LevenshteinSingleThread(expression, 1)); //Start multiple threads
   tasks.Add(task);
}
LevenshteinMatches[] results = Task.WaitAll(tasks); //Wait for all the threads to end.
Run Code Online (Sandbox Code Playgroud)

您甚至可以通过使用Parallel.For(一些for循环并使部分内部函数成为多线程,只要注意您调用的任何集合Add要么在一个内部同步,lock要么是线程安全的集合.

例如,如果SqueareLevenshtein内部是线程安全的,你可以这样做

Parallel.For(0, strLen, i => {
                                   //Are you sure ref is needed here?
    results[i] = SqueareLevenshtein(ref dimension[i], str.Substring(i, len).ToUpper(), expression, len);
});

LevenshteinMatches matches = new LevenshteinMatches();

Parallel.For(0, strLen; i => {
    if (results[i] <= maxDistance) {
        lock(matches)
        {
            matches.addMatch(str.Substring(i, len), Math.Round((1.0 - ((double)results[i] / len)) * 100.0, 2), i, len, results[i]);
        }
    }
});

return matches;
Run Code Online (Sandbox Code Playgroud)