如何将Java中的Handler转换为C#?附代码示例寻求技术帮助
Hey there! Let's figure out how to convert that Java Handler code into C#. First, let's recap what the original code does: it lazily creates an Android Handler that forwards incoming Message instances to the handleStateMessage method whenever a message arrives.
The approach in C# depends on what kind of project you're building—here are the two most common scenarios:
Scenario 1: UI-based Project (WPF, WinForms, UWP)
In UI frameworks, C# uses Dispatcher to manage thread-safe operations (similar to Android's Handler for UI thread tasks). You don't need to subclass anything; instead, you can use the built-in dispatcher to route calls to your HandleStateMessage method.
Here's the equivalent code:
private Dispatcher _dispatcher; protected Dispatcher GetHandler() { if (_dispatcher == null) { // Bind to the current thread's dispatcher (typically the UI thread) _dispatcher = Dispatcher.CurrentDispatcher; } return _dispatcher; } // Use this method to send messages, similar to Handler.sendMessage() protected void SendStateMessage(object messageData) { // Dispatch the call to the thread associated with the dispatcher GetHandler().Invoke(() => HandleStateMessage(messageData)); } // Your existing state-handling method (adjust the parameter type to match your needs) protected void HandleStateMessage(object messageData) { // Add your state processing logic here }
Key Notes:
Dispatcher.CurrentDispatchergets the dispatcher tied to the thread whereGetHandler()is first called (usually the UI thread, just like Android's Handler being bound to the thread it's created on).Invoke()ensuresHandleStateMessageruns on the dispatcher's thread, just like Android'shandleMessageruns on the Handler's thread.
Scenario 2: Non-UI Project (Console, Service, etc.)
If you're working in a non-UI environment where you need a custom message loop, you can build a simple Handler-like system using a message queue and background task.
Here's how to implement it:
// Custom message class to mirror Android's Message structure public class StateMessage { public int What { get; set; } // Equivalent to Message.what public object Obj { get; set; } // Equivalent to Message.obj } private BlockingCollection<StateMessage> _messageQueue; private Task _processingTask; private bool _handlerInitialized; protected void EnsureHandlerInitialized() { if (!_handlerInitialized) { _messageQueue = new BlockingCollection<StateMessage>(); // Start a background task to process messages continuously _processingTask = Task.Run(() => { foreach (var msg in _messageQueue.GetConsumingEnumerable()) { HandleStateMessage(msg); } }); _handlerInitialized = true; } } // Use this to send messages to the handler protected void SendStateMessage(StateMessage msg) { EnsureHandlerInitialized(); _messageQueue.Add(msg); } // Your state-handling method protected void HandleStateMessage(StateMessage msg) { // Process the message based on msg.What or msg.Obj here }
Key Notes:
BlockingCollectionacts as a thread-safe message queue, so you can add messages from any thread safely.- The background
Taskruns indefinitely, processing messages as they're added—just like Android's Looper processing messages for a Handler.
Final Tips
- If your original
handleStateMessageuses specific fields from Android'sMessage(likearg1,arg2), just add those properties to your customStateMessageclass. - For cleanup in non-UI projects, make sure to call
_messageQueue.CompleteAdding()when you're done to stop the processing task.
内容的提问来源于stack exchange,提问作者Zaid S Ahmed

