I want to implement a webchat.
The backend is a dual WCF channel. Dual channel works in the console or winforms,
and it actually works on the web. I can at least send and receive messages.
As a base I used this blog post
so, the async operation completes.
When i debug the result, I see that the messages are all ready to send to the browser.
[AsyncTimeout(ChatServer.MaxWaitSeconds * 1020)] // timeout is a bit longer than the internal wait
public void IndexAsync()
{
ChatSession chatSession = this.GetChatSession();
if (chatSession != null)
{
this.AsyncManager.OutstandingOperations.Increment();
try
{
chatSession.CheckForMessagesAsync(msgs =>
{
this.AsyncManager.Parameters["response"] = new ChatResponse { Messages = msgs };
this.AsyncManager.OutstandingOperations.Decrement();
});
}
catch (Exception ex)
{
Logger.ErrorException("Failed to check for messages.", ex);
}
}
}
public ActionResult IndexCompleted(ChatResponse response)
{
try
{
if (response != null)
{
Logger.Debug("Async request completed. Number of messages: {0}", response.Messages.Count);
}
JsonResult retval = this.Json(response);
Logger.Debug("Rendered response: {0}", retval.);
return retval;
}
catch (Exception ex)
{
Logger.ErrorException("Failed rendering the response.", ex);
return this.Json(null);
}
}
But nothing is actually sent.
Checking Fiddler, I see the request but I never get a response.
[SessionState(SessionStateBehavior.ReadOnly)]
public class ChatController : AsyncController
I also had to set the SessionStateBehaviour to Readonly, otherwise the async operation would block the whole page.
EDIT:
Here is the CheckForMessagesAsync:
public void CheckForMessagesAsync(Action<List<ChatMessage>> onMessages)
{
if (onMessages == null)
throw new ArgumentNullException("onMessages");
Task task = Task.Factory.StartNew(state =>
{
List<ChatMessage> msgs = new List<ChatMessage>();
ManualResetEventSlim wait = new ManualResetEventSlim(false);
Action<List<ChatMessage>> callback = state as Action<List<ChatMessage>>;
if (callback != null)
{
IDisposable subscriber = m_messages.Subscribe(chatMessage =>
{
msgs.Add(chatMessage);
wait.Set();
});
bool success;
using (subscriber)
{
// Wait for the max seconds for a new msg
success = wait.Wait(TimeSpan.FromSeconds(ChatServer.MaxWaitSeconds));
}
if (success) this.SafeCallOnMessages(callback, msgs);
else this.SafeCallOnMessages(callback, null);
}
}, onMessages);
}
private void SafeCallOnMessages(Action<List<ChatMessage>> onMessages, List<ChatMessage> messages)
{
if (onMessages != null)
{
if (messages == null)
messages = new List<ChatMessage>();
try
{
onMessages(messages);
}
catch (Exception ex)
{
this.Logger.ErrorException("Failed to call OnMessages callback.", ex);
}
}
}
it`s the same idea as the in the refered blog post
EDIT2:
Btw, when nothing is received, so the wait timeout comes into play, the reponse returns. so it seems to crash somewhere. any idea how to log this?
I changed the jQUERY request (see original blog post) from POST to GET. That fixes it.
Related
I have an async function which still freezes / lags the UI thread for me when I execute it. This is my function calling it.
private void TcpListenerLogic(object sender, string e)
{
Application.Current.Dispatcher.BeginInvoke((Action)async delegate {
try
{
dynamic results = JsonConvert.DeserializeObject<dynamic>(e);
if (results.test_id != null)
{
// Get properties for new anchor
string testInformation = await CommunicationCommands.getJsonFromURL(
"http://" + ServerIP + ":" + ServerPort + "/api/" + results.test_id);
}
}
catch (Exception exception)
{
// Writing some Trace.WriteLine()'s
}
});
}
And this is the async function that freezes my UI Thread
public static async Task<string> getJsonFromURL(string url)
{
try
{
string returnString = null;
using (System.Net.WebClient client = new System.Net.WebClient())
{
returnString = await client.DownloadStringTaskAsync(url);
}
return returnString;
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
return null;
}
}
I already tried to make everything in TcpListenerLogic run in a new Thread:
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
}).Start();
Which resulted in the whole UI completely freezing. And I tried to make TcpListenerLogic async and await the dispatcher, which also made everything freeze permanently. I also tried to make TcpListenerLogic async and leave the dispatcher. The dispatcher is only there because I normally have some UI code in there, which I left out for my tests.
I have ventured far through the internet, but no BackgroundWorker, ThreadPool or other methods helped me in my endeavour.
If anyone has help for this particular problem, or a resource that would improve my understanding of async functions in C#, I would much appreciate it.
Edit
As requested a deeper insight in how this event handler is called.
I have System.Net.Websocket, which is connected to the Backend API I am working with and triggers an event, everytime he receives new Data. To guarantee the socket listens as longs as it is open, there is a while loop which checks for the client state:
public event EventHandler<string> TcpReceived;
public async void StartListener(string ip, int port, string path)
{
try
{
using (client = new ClientWebSocket())
{
try
{ // Connect to backend
Uri serverUri = new Uri("ws://" + ip + ":" + port.ToString() + path );
await client.ConnectAsync(serverUri, CancellationToken.None);
}
catch (Exception ex)
{
BackendSettings.IsConnected = false;
Debug.WriteLine("Error connecting TCP Socket: " + ex.ToString());
}
state = client.State;
// Grab packages send in backend
while (client.State == WebSocketState.Open || client.State == WebSocketState.CloseSent)
{
try
{
// **Just formatting the received data until here and writing it into the "message" variable**//
TcpReceived(this, message);
// Close connection on command
if (result.MessageType == WebSocketMessageType.Close)
{
Debug.WriteLine("Closing TCP Socket.");
shouldstayclosed = true;
await client.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
break;
}
state = client.State;
}
catch
{
BackendSettings.IsConnected = false;
state = client.State;
}
}
state = client.State;
}
}
catch (Exception ex)
{
// Some error messages and settings handling
}
}
The Event has a handler attached:
TcpReceived += TcpListener_TcpReceived;
And this is the Handler, which calls the previously seen "TcpListenereLogic".
private void TcpListener_TcpReceived(object sender, string e)
{
TcpListenerLogic(sender, e);
//App.Current.Dispatcher.BeginInvoke(new Action(() => {
// TcpListenerLogic(sender, e);
//}));
//new Thread(() =>
//{
// Thread.CurrentThread.IsBackground = true;
// TcpListenerLogic(sender, e);
//}).Start();
}
I previously had the "TcpListenereLogic" as the handler, but I wanted to try different methods to call it. I also left in the commented out part, to show how the call of "TcpListenereLogic" looked already. All my attempts were with all mentioned setups and sadly lead to nothing.
Thank you very much #TheodorZoulias for helping me to find the solution to my problem.
It turns out it wasn't the async function itself, but rather how often it gets called. It got called roughly ~120 times every second.
My solution starts by calling the Listener method over a new Thread:
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
MainWindow.tcpListener.StartListener(ip, portNumber, "/api/");
}).Start();
To limit the amount of calls that happen every second I added a dispatcher timer, that resets a bool after it has been used for a call, by my Event.
readonly System.Windows.Threading.DispatcherTimer packageIntervallTimer =
new System.Windows.Threading.DispatcherTimer();
bool readyForNewPackage = true;
private void ReadyForPackage(object sender, EventArgs e)
{
readyForNewPackage = true;
}
public async void StartListener(string ip, int port, string path)
{
packageIntervallTimer.Interval = TimeSpan.FromMilliseconds(50);
packageIntervallTimer.Tick += (s, e) => { Task.Run(() => ReadyForPackage(s, e)); };
packageIntervallTimer.Start();
Then I wrapped everything inside the while loop into an if condition based on the bool, the most important part was to have my "event EventHandler TcpReceived" in there:
// Grab packages sent in backend
while (client.State == WebSocketState.Open || client.State == WebSocketState.CloseSent)
{
if (readyForNewPackage == true)
{
readyForNewPackage = false;
try
{
....
TcpReceived(this, message);
....
}
catch
{
...
}
}
}
I added my TcpListenerLogic to the Eventhandler:
TcpReceived += TcpListenerLogic;
And my TcpListenerLogic now looked like this (names have been changed):
private async void TcpListenerLogic(object sender, string e)
{
try
{
dynamic results = JsonConvert.DeserializeObject<dynamic>(e);
if (results.test_id != null)
{
string testID = "";
if (results.test_id is JValue jValueTestId)
{
testID = jValueTestId.Value.ToString();
}
else if (results.test_id is string)
{
testID = results.test_id;
}
// Get properties for new object
string information = await CommunicationCommands.getJsonFromURL(
"http://" + ServerIP + ":" + ServerPort + "/api/" + testID );
if (information != null)
{
await App.Current.Dispatcher.BeginInvoke(new Action(() =>
{
// Create object out of the json string
TestStatus testStatus = new TestStatus();
testStatus.Deserialize(information);
if (CommunicationCommands.isNameAlreadyInCollection(testStatus.name) == false)
{
// Add new object to the list
CommunicationCommands.allFoundTests.Add(testStatus);
}
}));
{
}
catch (Exception exception)
{
....
}
}
Adding a new Thread to execute any step results in problems, so keep in mind that all this uses the thread created at the beginning for "StartListener"
We have a siglnalR hub hosted in IIS, and a WPF .net core application that connects. Everything is working perfectly on first run. However, when IIS recycles the application pool, the WPF client re-reconnects successfully, but, (so it seems) on another thread, as when the user attempts to perform an action (open a new WPF window) - the following error is thrown when creating a new instance of the window to open :-
"The calling thread must be STA, because many UI components require this"
This is how we connect to the hub :-
private async void Connect()
{
try
{
_signalRConnection.On<Notification>(NotificationMessageStr, (message) =>
{
if (message != null && _signalRConnection != null)
{
OnProcessMessage(message);
}
}
);
_signalRConnection.Reconnecting += error =>
{
OnReconnecting("Connection lost - Attempting to reconnect.");
return Task.CompletedTask;
};
_signalRConnection.Reconnected += connectionId =>
{
OnReconnected("Reconnected");
return Task.CompletedTask;
};
_signalRConnection.Closed += error =>
{
OnLostConnection("Failed to connect");
// Notify users the connection has been closed or manually try to restart the connection.
return Task.CompletedTask;
};
try
{
//Connect to the server
await _signalRConnection.StartAsync();
}
catch (Exception ex)
{
}
}
catch (Exception ex)
{
}
}
When a message is received from the hub, we call :-
private void SubscriveToNewNotification()
{
vm.NewNotification += (sender, e) => {
ShowNotificationAlert(e.NotificationMessage); };
}
private void ShowNotificationAlert(Notification notification) {
NotificationAlert notificationAlert = new NotificationAlert();
notificationAlert.notification = notification;
notificationAlert.Show();
}
And it is this:-
NotificationAlert notificationAlert = new NotificationAlert();
That is failing.
This is how the connection is built up :-
private void InitializeViewModel()
{
try
{
string serviceAddress = "xxxx/notificationHub";
connectHub = NotificationHubManager.CreateNotificationHub(serviceAddress, userInfo);
}
catch (System.Exception ex)
{
System.Windows.MessageBox.Show(ex.Message + "--");
}
connectHub.ProcessMessage += (sender, e) =>
{
// THIS IS WHERE IT FALLS OVER
NotificationAlert n = new NotificationAlert();
OnNotificationReceived(e.NotificationMessage);
};
-- This is the notification hub
public static NotificationHubConnect CreateNotificationHub(string address, ISwiftUser userInfo = null)
{
HubConnection hubConnection = new HubConnectionBuilder()
.WithUrl(address)
.WithAutomaticReconnect()
.Build();
try
{
var result = new NotificationHubConnect(hubConnection, userInfo);
return result;
}
catch (Exception ex)
{
throw ex;
}
}
Is there a way to have the reconnect run on the same thread?
The solution works, but is there a better way to handle multiple requests like this with the errorhandling.
The below code describes what i want to do, and absolutely works. But I'm sure there is a better way to go about the issue?
I've tried other options as well but it fails as some of the requests will return a 404.
public async Task<List<Bruker>> TryGetContactsByContactIds(List<AZContact> contacts)
{
var tasks = contacts.Select(c => TryGetContactAsync(c.Email)).Where(c => c.Result != null);
try
{
var tasksresult = await Task.WhenAll(tasks);
return tasksresult.ToList();
}
catch (Exception e)
{
_logger.Error("unable to fetch all", e);
}
return new List<Bruker>();
}
public async Task<Bruker> TryGetContactAsync(string userId)
{
try
{
var user = await _brukereClient.GetAsync(userId);
return user;
}
catch (SwaggerException e)
{
if (e.StatusCode == 404)
{
_logger.Info($"user with Id {userId} does not exist");
}
else
{
_logger.Error("Unable to fetch user", e);
}
}
return null;
}
You are probably dealing with a feature/limitation of await, that throws only one of the aggregated exceptions of the awaited task (the WhenAll task in this case). You must enumerate all the tasks to handle each individual exception.
try
{
var tasksresult = await Task.WhenAll(tasks);
return tasksresult.ToList();
}
catch (Exception e)
{
foreach (var task in tasks)
{
if (task.IsFaulted)
{
var taskException = task.Exception.InnerException;
// ^^ Assuming that each task cannot have more than one exception inside its AggregateException.
if (taskException is SwaggerException swaggerException)
{
if (swaggerException.StatusCode == 404)
{
_logger.Info($"user with Id {userId} does not exist");
}
else
{
_logger.Error("Unable to fetch user", swaggerException);
}
}
else
{
_logger.Error("An unexpected task error occurred", taskException);
}
}
}
if (!tasks.Any(t => t.IsFaulted))
{
_logger.Error("A non task-related error occurred", e);
}
}
I saw several posts with similar problem but no solution works :/
I debug a windows service by using a console application. It executes tasks on website and must be able to collect http code status for create logs. As you can see, sensitive code is in try/catch.
When I debug (F5), I have a WebException that is not caught. When I run (CTRL + F5), the exception's message is write in my console and stops my program.
This is my code :
public partial class Schedulor : ServiceBase
{
void RunTasks()
{
schedulor.Start();
List<Task> task = new List<Task>();
foreach (TaskPlanner tp in listTp)
{
if (tp.CountDown == 0 && tp.IsRunning == false)
{
// Initialisation lors de GetTasks()
tp.IsRunning = true;
try
{
task.Add(Task.Factory.StartNew(() => tr = tp.ExecuteBot.Execute())); // WEBEXECPTION HERE (cannot find 404)
}
catch (Exception e)
{
if (e is WebException)
{
// treatment
}
}
}
}
Task.WaitAll(task.ToArray());
CreateLogs();
}
}
public class Bot : IBot
{
public TaskResult Execute()
{
TaskResult tr = new TaskResult();
int codeResponse, timeout;
string credentials;
try
{
WebRequest wrSettings = WebRequest.Create(settings.Url);
// treatment
}
catch (Exception e)
{
//Console.WriteLine(e.Message);
if (e is WebException)
{
var code = ((HttpWebResponse)((WebException)e).Response).StatusCode;
if ((int)code != settings.HttpResponse)
{
tr.MyResult = TaskResult.Result.nok;
goto next;
}
else tr.MyResult = TaskResult.Result.ok;
}
}
next:
return tr;
}
}
I do not understand why my catch does not work. I need to treat this information because the task can test if a website return 404 or anything else.
Thanks in advance
EDIT : -----------
I reduce code as it requests because deleted code does not the real problem
You should catch that exception in task. Add another method, and create your tasks similar to:
task.Add(Task.Factory.StartNew(() => Process(tp)));
void Process(TaskPlanner tp)
{
try
{
tp.ExecuteBot.Execute();
}
catch (WebException wex)
{
}
}
We have an asynchronous WCF service operation that gets log files from all of the different components of our system and sends them to the client. Since this could take a while if one of the components isn't working right, it would be nice if this functionality won't time out, but it shouldn't cause the client to hang either.
My understanding of asynchronous WCF services is that when the client asks the server for something, the server immediately responds with a message saying, "I'm on it. Keep on doing your own stuff, and I'll let you know when I'm finished." Then the connection is freed up for the client to make other requests while the server spins up a new thread to do the bulk of its work. When the server is finished, it sends a message back to the client with the results. Because of this, the connection between the server and client is free, and regardless of how long the server takes, the connection should never time out. Is this correct?
If that's the case, then our service isn't working as expected. When I test the service, it works as expected as long as it takes less than a minute. If I force it to take longer than that, though, the client throws a TimeoutException. Since the service is asynchronous, shouldn't it never time out? If so, what am I missing?
We wrote our asynchronous service using this page as a guide:
http://code.msdn.microsoft.com/windowsdesktop/How-to-Implement-a-WCF-2090bec8
Here is my code. This is the service contract:
[ServiceContract(CallbackContract = typeof(IInformationServiceCallBack), SessionMode = SessionMode.Required)]
public interface IInformationService
{
//snip...
[OperationContract(AsyncPattern=true)]
[FaultContract(typeof(LogFileFault))]
IAsyncResult BeginGetLogFiles(LogFileRequest[] logfileRequests,
AsyncCallback callback, object state);
LogFile[] EndGetLogFiles(IAsyncResult result);
//snip...
}
This is the service implementation:
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerSession, UseSynchronizationContext=false)]
public class InformationServiceImpl : IInformationService, IDisposable
{
//snip...
public IAsyncResult BeginGetLogFiles(LogFileRequest[] logfileRequests,
AsyncCallback callback, object state)
{
var task = Task<LogFile[]>.Factory.StartNew((x) =>
{
return GetLogFilesHelper(logfileRequests);
}, state);
return task.ContinueWith(res => callback(task));
}
public LogFile[] EndGetLogFiles(IAsyncResult result)
{
var castResult = result as Task<LogFile[]>;
return castResult.Result;
}
private LogFile[] GetLogFilesHelper(LogFileRequest[] logfileRequests)
{
//Long-running method that gets the log files
}
//snip...
}
Here is the client-side code:
public class InformationServiceConnection : WcfDurableConnection<IInformationService> //WcfDurableConnection is one of our internal classes
{
//snip...
public void GetServiceLogFiles(Action<LogFile[], WcfCommandResult> callback)
{
var logfileRequests = new LogFileRequest[]
{
new LogFileRequest(/* snip */),
new LogFileRequest(/* snip */),
new LogFileRequest(/* snip */),
new LogFileRequest(/* snip */)
};
ExecuteTask(x =>
{
LogFile[] logfile = null;
WcfCommandResult wcfResult = null;
var asyncCallback = new AsyncCallback((result) =>
{
logfile = Channel.EndGetLogFiles(result);
callback(logfile, wcfResult);
});
wcfResult = RunCommand(y =>
{
Channel.BeginGetLogFiles(logfileRequests, asyncCallback, null);
}, x);
});
}
/* ExecuteTask and RunCommand are both methods that take care of
* multithreading issues for us. I included their code below in
* case they make a difference, but the code I'm most interested
* in is the GetServiceLogFiles method above. */
//snip...
protected CancellationTokenSource ExecuteTask(Action<CancellationToken> action)
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
ManualResetEvent lastTask;
ManualResetEvent thisTask;
lock (_objectLock)
{
lastTask = _syncTask;
thisTask = new ManualResetEvent(false);
_syncTask = thisTask;
}
tokenSource.Token.Register(x => ((ManualResetEvent)x).Set(), thisTask);
var task = Task.Factory.StartNew((x) =>
{
try
{
lastTask.WaitOne();
action((CancellationToken)x);
}
catch (Exception e)
{
LogUtility.Error(e);
}
finally
{
thisTask.Set();
}
}, tokenSource.Token, tokenSource.Token).HandleExceptions();
return tokenSource;
}
//snip...
protected WcfCommandResult RunCommand(Action<CancellationToken> action, CancellationToken token, bool isRestarting = false)
{
return RunCommand(x => { action(x); return true; }, token, isRestarting);
}
protected WcfCommandResult RunCommand(Func<CancellationToken, bool> action, CancellationToken token, bool isRestarting = false)
{
WcfCommandResult result = new WcfCommandResult();
lock (_reconnectionLock)
{
if (_reconnecting && !isRestarting)
{
result.Completed = false;
return result;
}
}
lock (_channelLock)
{
if (Channel == null && !_closing)
{
token.ThrowIfCancellationRequested();
Channel = GetNewChannel();
var iChannel = (IClientChannel)Channel;
var initResult = Initialize(token, false);
if (initResult.Completed)
{
Connected = true;
LogUtility.Info(string.Format("Connected to {0} at {1}", ServiceName, iChannel.RemoteAddress));
}
else
LogUtility.Info(string.Format("Failed to connect to {0} at {1}", ServiceName, iChannel.RemoteAddress));
}
}
try
{
var channel = Channel;
token.ThrowIfCancellationRequested();
if (channel != null)
result.Completed = action(token);
}
catch (FaultException e)
{
result.Exception = e;
result.Detail = e.GetDetail<DurableFault>();
LogUtility.Error(result.Exception);
}
catch (CommunicationException e)
{
Connected = false;
result.Exception = e;
IClientChannel channel = ((IClientChannel)Channel);
if (channel != null)
channel.Abort();
Channel = null;
if (!_reconnecting)
LogUtility.Error(result.Exception);
}
catch (TimeoutException e)
{
Connected = false;
result.Exception = e;
IClientChannel channel = ((IClientChannel)Channel);
if (channel != null)
channel.Abort();
Channel = null;
if (!_reconnecting)
LogUtility.Error(result.Exception);
}
catch (NullReferenceException e)
{
Connected = false;
result.Exception = e;
IClientChannel channel = ((IClientChannel)Channel);
if (channel != null)
channel.Abort();
Channel = null;
if (!_reconnecting)
LogUtility.WriteException("Channel is null, it has either been disposed or not setup, call BeginSetupUser to create a new channel", e);
}
catch (ObjectDisposedException e)
{
Connected = false;
result.Exception = e;
IClientChannel channel = ((IClientChannel)Channel);
if (channel != null)
channel.Abort();
Channel = null;
if (!_reconnecting)
LogUtility.Error(result.Exception);
}
catch (InvalidOperationException e)
{
Connected = false;
result.Exception = e;
IClientChannel channel = ((IClientChannel)Channel);
if (channel != null)
channel.Abort();
Channel = null;
if (!_reconnecting)
LogUtility.Error(result.Exception);
}
return result;
}
//snip...
}
There is a timeout set in your config file even for asynchronous calls. You should probably increase it if it will take a long time to respond. I think default is 1 minute. In visual studio, go to tools-> WCF Service Configuration Editor to easily change the value.
This may also help you if you want to see what the configuration looks like: Increasing the timeout value in a WCF service
You can set it in that config file, or in the code behind.