It's essentially a less-efficient version of Delay with WhenAny. Method #3: Uses StartNew just to call Delay - not sure of the reasoning there. In this case, it would probably work OK since the CTS is always eventually cancelled. Method #2: Normally, you should be disposing the result of Register once the task completes. It's just a less-efficient version of Method #2. Method #1: Creates a new CancellationToken for no reason. Var completedTask = await Task.WhenAny(requestTask, timeoutTask) Var timeoutTask = Task.Delay(timeoutInSeconds) Task requestTask = GetDataFromServerAsync() I think it's easier to just use Task.Delay and Task.WhenAny: public async Task GetDataFromServerAsync(int timeoutInSeconds) One piece of knowledge I found out the hard way - if you call GetDataFromServer() from a thread besides the main UI thread: Task.Run(() => await GetDataFromServer()) What are the plusses and minuses to the 4 different ways of setting up a timeout? For instance, I'm guessing that method #2 is the most "lightweight" (requiring the fewest system resources)?Īre there other ways to set up a timeout that I've missed? Factory.StartNew (async () =>Īwait .Delay (timeoutInSeconds * 1000) Public Task GetDataFromServer(int timeoutInSeconds)ĬancellationToken ct = new CancellationToken () ĬancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource (ct) Ĭts.CancelAfter (timeoutInSeconds * 1000) Ĭts.Token.Register(() => m_source.TrySetCancelled()) ĬancellationTokenSource ct2 = new CancellationTokenSource () Ĭt2.CancelAfter (timeoutInSeconds * 1000) Ĭt2.Token.Register (() => m_source.TrySetCancelled()) ![]() I have several options for doing this: class M圜lass Now I want this to be a little smarter, and time itself out when appropriate. System call I have no visibility into, and that doesn't inherently take anyĪsk_server_for_data_and_when_youve_got_it_call(Callback) The initial code looks like this: class M圜lass Like many others, I need to write a function that returns a task, and I want that task to automatically time out after a certain period.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |