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 #include "base/win/object_watcher.h"
8 #include "base/logging.h"
13 //-----------------------------------------------------------------------------
15 ObjectWatcher::ObjectWatcher()
16 : weak_factory_(this),
22 ObjectWatcher::~ObjectWatcher() {
26 bool ObjectWatcher::StartWatching(HANDLE object
, Delegate
* delegate
) {
29 NOTREACHED() << "Already watching an object";
33 // Since our job is to just notice when an object is signaled and report the
34 // result back to this thread, we can just run on a Windows wait thread.
35 DWORD wait_flags
= WT_EXECUTEINWAITTHREAD
| WT_EXECUTEONLYONCE
;
37 // DoneWaiting can be synchronously called from RegisterWaitForSingleObject,
38 // so set up all state now.
39 callback_
= base::Bind(&ObjectWatcher::Signal
, weak_factory_
.GetWeakPtr(),
42 origin_loop_
= MessageLoop::current();
44 if (!RegisterWaitForSingleObject(&wait_object_
, object
, DoneWaiting
,
45 this, INFINITE
, wait_flags
)) {
46 DLOG_GETLASTERROR(FATAL
) << "RegisterWaitForSingleObject failed";
52 // We need to know if the current message loop is going away so we can
53 // prevent the wait thread from trying to access a dead message loop.
54 MessageLoop::current()->AddDestructionObserver(this);
58 bool ObjectWatcher::StopWatching() {
62 // Make sure ObjectWatcher is used in a single-threaded fashion.
63 DCHECK_EQ(origin_loop_
, MessageLoop::current());
65 // Blocking call to cancel the wait. Any callbacks already in progress will
66 // finish before we return from this call.
67 if (!UnregisterWaitEx(wait_object_
, INVALID_HANDLE_VALUE
)) {
68 DLOG_GETLASTERROR(FATAL
) << "UnregisterWaitEx failed";
72 weak_factory_
.InvalidateWeakPtrs();
76 MessageLoop::current()->RemoveDestructionObserver(this);
80 HANDLE
ObjectWatcher::GetWatchedObject() {
85 void CALLBACK
ObjectWatcher::DoneWaiting(void* param
, BOOLEAN timed_out
) {
88 // The destructor blocks on any callbacks that are in flight, so we know that
89 // that is always a pointer to a valid ObjectWater.
90 ObjectWatcher
* that
= static_cast<ObjectWatcher
*>(param
);
91 that
->origin_loop_
->PostTask(FROM_HERE
, that
->callback_
);
92 that
->callback_
.Reset();
95 void ObjectWatcher::Signal(Delegate
* delegate
) {
96 // Signaling the delegate may result in our destruction or a nested call to
97 // StartWatching(). As a result, we save any state we need and clear previous
98 // watcher state before signaling the delegate.
99 HANDLE object
= object_
;
101 delegate
->OnObjectSignaled(object
);
104 void ObjectWatcher::WillDestroyCurrentMessageLoop() {
105 // Need to shutdown the watch so that we don't try to access the MessageLoop