Have developed an Azure service bus message receiver console app which is working fine console app.
Code for console app as follows:
using System.IO;
using Microsoft.ServiceBus.Messaging;
class Program
{
static void Main(string[] args)
{
const string connectionString = "Endpoint=sb://sbusnsXXXX.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=bkjk3Qo5QFoILlnay44ptlukJqncoRUaAfR+KtZp6Vo=";
const string queueName = "bewtstest1";
var queueClient = QueueClient.CreateFromConnectionString(connectionString, queueName);
try
{
queueClient.OnMessage(message => {
string body = new StreamReader(message.GetBody<Stream>(), Encoding.UTF8).ReadToEnd();
Console.WriteLine(body);
message.Complete();
});
Console.ReadLine();
}
catch (Exception ex)
{
queueClient.OnMessage(message => {
Console.WriteLine(ex.ToString());
message.Abandon();
});
Console.ReadLine();
}
}
}
Have tried to convert to a WinForms app, so I can show the service bus message as a string in a ListBox.
I have created a new Class (Azure
) with the console app code, and call the method in the main form.
Class Azure:
using System.IO;
using Microsoft.ServiceBus.Messaging;
public class Azure
{
public static void GetQueue(Form1 form)
{
const string connectionString = "Endpoint=sb://sbusnsXXXX.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=bkjk3Qo5QFoILlnay44ptlukJqncoRUaAfR+KtZp6Vo=";
const string queueName = "bewtstest1";
var queueClient = QueueClient.CreateFromConnectionString(connectionString, queueName);
try
{
queueClient.OnMessage(message => {
string body = new StreamReader(message.GetBody<Stream>(), Encoding.UTF8).ReadToEnd();
//Form1 f = new Form1();
form.listBox1.Items.Add(body);
Console.WriteLine(body);
message.Complete();
});
Console.ReadLine();
}
catch (Exception ex)
{
queueClient.OnMessage(message => {
Console.WriteLine(ex.ToString());
message.Abandon();
});
Console.ReadLine();
}
}
}
Main Form:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Azure.GetQueue(this);
}
}
The code compiles, however when a new service bus message is received I get the following exception:
System.InvalidOperationException: 'Cross-thread operation not valid: Control 'listBox1' accessed from a thread other than the thread it was created on.'
Any thoughts on how I can avoid this exception (note I have tried using InvokeRequired
but can't get the code to compile)?
(Feel like I'm close as when I stop and re-run the program, the form loads with the message in the ListBox as shown here: listbox with message!)