Reputation: 446
Or do I have to use Task.Run within the method to make sure each function exists on its own thread? I'm trying to see if there's any wisdom in this practice I see in the code I'm working on.
public async Task<string> GetAStringAfterSyncProcessing(string processThis) {
return await Task.Run(async () => {
var processThis2 = processThis + ",";
var processThis3 = processThis2 + ",";
var nowImDone = processThis3 + ",";
return nowImDone;
});
}
I have a feeling that this is unintended design, since it makes it impossible to walk through each line while debugging. So I'm wondering if I'd be right in explaining to others that async automatically implies the creating of a new thread so that the function is only called when await or .GetAwaiter().GetResult() is used. Thanks
Upvotes: 1
Views: 110
Reputation: 1502066
No, async
itself does not create a new thread.
And there's no point in using async
/await
in the code you've demonstrated. It's mostly equivalent to:
public Task<string> GetAStringAfterSyncProcessing(string processThis) {
return Task.Run(() => {
var processThis2 = processThis + ",";
var processThis3 = processThis2 + ",";
var nowImDone = processThis3 + ",";
return nowImDone;
});
}
(I've removed the async lambda too, which was unnecessary.)
Next:
So I'm wondering if I'd be right in explaining to others that async automatically implies the creating of a new thread so that the function is only called when await or .GetAwaiter().GetResult() is used.
No, that's definitely not the right explanation at all. It's hard to give the full low-down on it in just an SO answer, but I strongly suggest you go and read the MSDN resources on what async/await is actually about. There's an expectation that whatever you await will be inherently asynchronous - where that's because it starts a thread itself, or because it doesn't need a thread in order to be asynchronous (e.g. async IO).
Upvotes: 3