Cancel AsyncTask after some time

后端 未结 5 459
别那么骄傲
别那么骄傲 2020-12-31 06:11

This could be a duplicate question but I did not find what I was looking for. I am calling an AsyncTask in the UI activity new LoadData().execute(); and in doI

5条回答
  •  感情败类
    2020-12-31 06:50

    I would translate this into an async/await problem making all the expensive methods as async methods.

    First, Modify DataCollector's collectData(query) to collectDataAsync(query). (If you can't modify DataCollector, there are work arounds to wrap it in a lambda function or something similar).

    Second, change doInBackground as an async task, something like this:

    protected async Task doInBackgroundAsync(String... args)
    {
        DataCollector dc = new DataCollector();
        int timeout = 1000;
        var task = dc.collectDataAsync(query);
        if (await Task.WhenAny(task, Task.Delay(timeout)) == task) {
            // task completed within timeout
            data = task.Result;
        } else { 
            // timeout logic
        }
    }
    

    Basically, you have two tasks inside doInBackgroundAsync: collectDataAsync and a delay task. Your code waits for the faster one. Then you know which one was and you can react accordingly.

    If you also need to cancel collectDataAsync task, then you want to used a cancellationToken. I use this to solve your problem https://stackoverflow.com/a/11191070/3307066.

    Note that now doInBackgroundAsync is a async, so it changes a bit the way of using it.

    Hope it helps.

提交回复
热议问题