1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef CHROME_BROWSER_ANDROID_PROVIDER_BLOCKING_UI_THREAD_ASYNC_REQUEST_H_
6 #define CHROME_BROWSER_ANDROID_PROVIDER_BLOCKING_UI_THREAD_ASYNC_REQUEST_H_
9 #include "base/callback.h"
10 #include "base/synchronization/waitable_event.h"
11 #include "chrome/browser/android/provider/run_on_ui_thread_blocking.h"
12 #include "content/public/browser/browser_thread.h"
14 // Allows making async requests and blocking the current thread until the
15 // response arrives. The request is performed in the UI thread.
16 // Users of this class MUST call RequestCompleted when receiving the response.
17 // Cannot be called directly from the UI thread.
18 class BlockingUIThreadAsyncRequest
{
20 BlockingUIThreadAsyncRequest();
22 // Runs an asynchronous request, blocking the invoking thread until a response
23 // is received. Class users MUST call RequestCompleted when this happens.
24 // Make sure that the response is also delivered to the UI thread.
25 // The request argument can be defined using base::Bind.
26 template <typename Signature
>
27 void RunAsyncRequestOnUIThreadBlocking(base::Callback
<Signature
> request
) {
28 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
30 // Make the request in the UI thread.
31 request_completed_
.Reset();
32 RunOnUIThreadBlocking::Run(
34 &BlockingUIThreadAsyncRequest::RunRequestOnUIThread
<Signature
>,
37 // Wait until the request callback invokes Finished.
38 request_completed_
.Wait();
41 // Notifies about a finished request.
42 void RequestCompleted();
45 template <typename Signature
>
46 static void RunRequestOnUIThread(base::Callback
<Signature
> request
) {
50 base::WaitableEvent request_completed_
;
52 DISALLOW_COPY_AND_ASSIGN(BlockingUIThreadAsyncRequest
);
55 #endif // CHROME_BROWSER_ANDROID_PROVIDER_BLOCKING_UI_THREAD_ASYNC_REQUEST_H_