// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // CancelableOnceCallback is a wrapper around OnceCallback that allows // cancellation of the callback. CanacelableRepeatingCallback is the same sort // of wrapper around RepeatingCallback. The wrapper takes a reference on the // wrapped callback until this object is destroyed or Reset()/Cancel() are // called. // // NOTE: // // Calling Cancel() brings the object back to its natural, default-constructed // state, i.e., callback() will return a null callback. // // THREAD-SAFETY: // // Cancelable callback objects must be created on, posted to, cancelled on, and // destroyed on the same SequencedTaskRunner. The wrapper returned by callback() // must also be run on this SequencedTaskRunner, but it may be destroyed on any // sequence; see comments on callback(). // // // EXAMPLE USAGE: // // In the following example, the test is verifying that RunIntensiveTest() // Quit()s the message loop within 4 seconds. The cancelable callback is posted // to the message loop, the intensive test runs, the message loop is run, // then the callback is cancelled. // // RunLoop run_loop; // // void TimeoutCallback(const std::string& timeout_message) { // FAIL() << timeout_message; // run_loop.QuitWhenIdle(); // } // // CancelableOnceClosure timeout( // base::BindOnce(&TimeoutCallback, "Test timed out.")); // SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( // FROM_HERE, timeout.callback(), Seconds(4)); // RunIntensiveTest(); // run_loop.Run(); // timeout.Cancel(); // Hopefully this is hit before the timeout callback runs. // #ifndef BASE_CANCELABLE_CALLBACK_H_ #define BASE_CANCELABLE_CALLBACK_H_ #include <utility> #include "base/check.h" #include "base/compiler_specific.h" #include "base/functional/bind.h" #include "base/functional/callback.h" #include "base/functional/callback_internal.h" #include "base/memory/weak_ptr.h" namespace base { namespace internal { template <typename CallbackType> class CancelableCallbackImpl { … }; } // namespace internal // Consider using base::WeakPtr directly instead of base::CancelableOnceCallback // for task cancellation. CancelableOnceCallback; CancelableOnceClosure; CancelableRepeatingCallback; CancelableRepeatingClosure; } // namespace base #endif // BASE_CANCELABLE_CALLBACK_H_