Reputation: 1913
Given code like this:
static void A() {
string input = "abcabcabc";
string pattern = "a";
string result = Regex.Replace(input, pattern, match => Evaluator(match));
}
static string Evaluator(Match match) {
return "d";
}
Is there any way to use async/await with a delegate like this?
This:
static void B() {
string input = "abcabcabc";
string pattern = "a";
string result = Regex.Replace(input, pattern, async match => await EvaluatorAsync(match));
}
static async Task<string> EvaluatorAsync(Match match) {
return "d";
}
...doesn't work - the error message is 'The return type of an async method must be void, Task or Task'.
Upvotes: 2
Views: 857
Reputation: 13495
The third parameter you are passing to Regex.Replace
must be of type
[SerializableAttribute]
public delegate string MatchEvaluator(
Match match
)
you are passing in an async
delegate whose return type is Task<string>
. You can do
string result = Regex.Replace(input, pattern, match => EvaluatorAsync(match).Result);
but it will block until the result is available which defeats the purpose and also it can cause a deadlock. As higlighted in this answer Regex searches are CPU bound so async
will not help you there. The best you can do is use Task.Run
to push the work to a background thread.
Upvotes: 2