private void AirTransit_Load(object sender, EventArgs e) { DialogResult LoginCompleted; using (FormLogin login = new FormLogin()) { LoginCompleted = login.ShowDialog(); PhoneNumber = login.PhoneNumber; } if (LoginCompleted == DialogResult.Abort) { MessageBox.Show("Login aborted. Closing..."); Close(); } else { if (Core.Init(phoneNumber)) { ContactRepo = Core.ContactRepository; MessageRepo = Core.MessageRepository; MessageService = Core.MessageService; Contacts = new ConcurrentBag <Contact>(ContactRepo.GetContacts().ToList()); newMessageIds = Core.GetBlockingCollection(); // Based on : https://docs.microsoft.com/en-us/dotnet/standard/collections/thread-safe/blockingcollection-overview Task.Run(() => { while (!newMessageIds.IsCompleted) { Message message = null; // Blocks if number.Count == 0 // IOE means that Take() was called on a completed collection. // Some other thread can call CompleteAdding after we pass the // IsCompleted check but before we call Take. // In this example, we can simply catch the exception since the // loop will break on the next iteration. try { message = newMessageIds.Take(); } catch (InvalidOperationException) { } if (message != null) { ProcessNewMessage(message); } } }); if (ListContacts.SelectedItem == null && ListContacts.Items.Count > 0) { ListContacts.SelectedIndex = 0; } } else { MessageBox.Show("An error as occur during initialization. Closing."); Close(); } } }
private void ProcessNewMessage(Message newMessage) { Contact senderContact = newMessage.Sender; if (senderContact.Id == selectedContact.Id) { PrintMessage(newMessage); } else if (!Contacts.Contains(senderContact)) { // Adds the new contact to the contacts list Contacts.Add(senderContact); } }
private void PrintMessage(Message message) { if (message == null) { return; } if (Txtconversation.InvokeRequired) { MessageArgReturningVoidDelegate d = PrintMessage; Invoke(d, message); } else { bool currentlyUser = message.DestinationPhoneNumber != PhoneNumber; Txtconversation.SelectionColor = currentlyUser ? UserColor : ContactColor; if (WasUser != currentlyUser || Txtconversation.TextLength == 0) { AppendTextSafely($"{message.Sender.Name} :"); WasUser = currentlyUser; } AppendTextSafely(message.Content + Environment.NewLine); } }