I have an win8 app and I want to add proggress ring while app gets info from server.
but when
proggressRing.isActivate = true;
checkServer();
the app freezes until returns from checkServer() and proggressRing does not activates when it freezes.
I asked around and said you have to use multi threading
how can I use multi thread in c# or is there any other way?
thanks
There are multiple solutions to this
1) first ensure that CheckServer is implemented as Async Task (Async Event based can still be used).
2) If it is CPU intensive operation, use Task.Run to queue the Task to run on a threadpool thread.
have a look at this post
http://msdn.microsoft.com/en-us/library/windows/apps/hh452713.aspx and this one
http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx
Related
We created a Qt HTTP server derived from QTcpServer.
Each incoming client connection is handled in a new thread like this:
void WebClientThread::run()
{
// Configure the web client socket
m_socket = new QTcpSocket();
connect(m_socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
connect(m_socket, SIGNAL (error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
// Create the actual web client = worker
WebClient client(m_socket, m_configuration, m_pEventConnection, m_pThumbnailStreams, m_server, m_macAddress, 0 );
// Thread event loop
exec();
m_pLog->LOG(L_INFO, "Webclient thread finished");
}
//
// Client disconnect
//
void WebClientThread::disconnected()
{
m_socket->deleteLater();
exit(0);
}
This code works, but we experienced application crashes when it was executed while the NTP connection of our device kicked in and the system time was corrected from the epoch 01/01/1970 to the current time.
The crash could also be reproduced when running the application and meanwhile changing the system time from a script.
The application runs fine - even when the system time changes on the fly like this:
void WebClientThread::run()
{
// Configure the web client socket
m_socket = new QTcpSocket();
connect(m_socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
connect(m_socket, SIGNAL (error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
// Create the actual web client = worker
WebClient client(m_socket, m_configuration, m_pEventConnection, m_pThumbnailStreams, m_server, m_macAddress, 0 );
// Make this thread a loop,
exec();
delete m_socket;
m_pLog->LOG(L_INFO, "Webclient thread finished");
}
//=======================================================================
//
// Client disconnect
//
void WebClientThread::disconnected()
{
exit(0);
}
Why would deleteLater() crash the application when the system time is shifted ?
Additional information:
OS = embedded linux 3.0.0. Qt = 4.8
The socket is a connection between our Qt web server application and the front end server = lighttpd. Could it be that lighttpd closes the socket when the system time shifts 47 years and the request is still being processed by our web server?
I could reproduce it by sending requests to the server while in parallel running a script that sets date to 1980, 1990 and 2000. It changes once a second.
This smells of wrong use of Qt threads. I suggest you do not subclass QThread, if you call exec() from its run() method, because it's just too easy to do things wrong way if you do that.
See for example https://wiki.qt.io/QThreads_general_usage to see how to set up a worker QObject for a QThread, but the gist of it is, create subclass of QObject and put your code there. Then move an instance of that to a QThread instance, and connect signals and slots to make things happen.
Another things, you normally shouldn't use threads for Qt Networking, like QTcpSocket. Qt is event based and asynchronous, and as long as you just use signals and slots and never block in your slot methods, there is no need for threads, they only complicate things for no benefit. Only if you have time-consuming calculations, or if your program truly needs to utilize multiple CPU cores to achieve good enough performance, only then look into multithreading.
I am working on application that utilizes RxJava, realm and retrofit.
I need to create very specific data processing chain. I need to perform Retrofit calls on the io scheduler, then process provided data on my custom single-thread realm scheduler, and then push results out to my ui on mainThread scheduler. I tried to do this by using multiple combinations of observeOn and subscribeOn but I can't get the middle part to execute on realm sheduler.
my goal is something like this
scheduler: io ---------------> realm -----------------> mainthread
action : retrofit call-----> database update -------> ui update
How can I create such chain of observables, where each observable work is done on specific thread ?
Thank you
Look into the Observable.observeOn(...) method. This method will make sure all operations that happen after occur on the provided Scheduler.
To support your custom "realm" scheduler you will need to provide some way for RxJava to schedule work. If you're using a standard Executor (like Executors.newSingleThreadExecutor() to support Realm's single-thread policy) then you can use Schedulers.from(Executor) to create a scheduler that will execute on that specific Executor.
ExecutorService realm = Executors.newSingleThreadExecutor();
Scheduler realmScheduler = Schedulers.from(realm);
Retrofit source;
source.call()
.subscribeOn(Schedulers.io())
.observeOn(realmScheduler)
.map(DataBaseUpdate)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(UIUpdate)
Hello i am new to developing application. now i am working on an app that have to track the location so it must work in the background when i do so it works will but when i get back to the app the UI is not updated
if (!App.RunningInBackground)
{
Dispatcher.BeginInvoke(() =>
{
one.Text = args.Position.Coordinate.Latitude.ToString();
two.Text = args.Position.Coordinate.Longitude.ToString();
});
}
and on the output
The thread 0x7b4 has exited with code 259 (0x103).
i do not know what is UI thread and i checked Google.
If you want to have an app that runs in background, you should use background agents.
For a good quick start this link is best.
Best practices and advices are found here.
And you want to run your app in background and want to update the textbox in foreground? what do you mean?
UI thread means the main thread in phone foreground app where all the activities take place. Any new async task has to be spawned from this UI thread only.
You have a code because your app has successfully exited the foreground.
I'm using MVC4 ApiController to upload data to Azure Blob. Here is the sample code:
public Task PostAsync(int id)
{
return Task.Factory.StartNew(() =>
{
// CloudBlob.UploadFromStream(stream);
});
}
Does this code even make sense? I think ASP.NET is already processing the request in a worker thread, so running UploadFromStream in another thread doesn't seem to make sense since it now uses two threads to run this method (I assume the original worker thread is waiting for this UploadFromStream to finish?)
So my understanding is that async ApiController only makes sense if we are using some built-in async methods such as HttpClient.GetAsync or SqlCommand.ExecuteReaderAsync. Those methods probably use I/O Completion Ports internally so it can free up the thread while doing the actual work. So I should change the code to this?
public Task PostAsync(int id)
{
// only to show it's using the proper async version of the method.
return TaskFactory.FromAsync(BeginUploadFromStream, EndUploadFromStream...)
}
On the other hand, if all the work in the Post method is CPU/memory intensive, then the async version PostAsync will not help throughput of requests. It might be better to just use the regular "public void Post(int id)" method, right?
I know it's a lot questions. Hopefully it will clarify my understanding of async usage in the ASP.NET MVC. Thanks.
Yes, most of what you say is correct. Even down to the details with completion ports and such.
Here is a tiny error:
I assume the original worker thread is waiting for this UploadFromStream to finish?
Only your task thread is running. You're using the async pipeline after all. It does not wait for the task to finish, it just hooks up a continuation. (Just like with HttpClient.GetAsync).
I am trying solve this problem. I have WCF service. Client can call web method from this service which only "fire" another method (this method only write data to database) in another thread.
Code is here:
//this method will write data to database
public void WriteToDb()
{
}
//this web method will call only mehod WriteToDb() in another thread
public void SomeWebMethod()
{
new Task(WriteToDb).Start();
}
Problem is that in same time can web method call 5 clients. This cause that method WriteToDb is called 5 times in 5 thread.
In all 5 cases method WriteToDb will use same data.
My aim is achieve this behavior. 5 clients called web method SomeWebMethod. Method WriteToDb will run in 5 thread.
But I would like execute first thread, then second thread ....etc and on the end 5th thread.
I don’t want run method WriteToDb in same time in 5 thread.
So maybe I can use lock.
{
private object locker = new object();
//this method will write data to database
public void WriteToDb()
{
lock(locker)
{
//write to DB
}
}
I am not sure because .net assembly is host on app domain a app domain is host on win process. I woud like to avoid deadlocks.
What happens if I have a machine with 6 CPU? Use mutex instead lock ?
Thank you for help...
I'm not particulary sure what you are writing to DB, but your question is loosely coupled with WCF to be frank, try to read CLR via C# on multithreading etc.
Also regarding WCF, you can setup how your service object is created upon requests, ie per call, per session or singleton, and for later use specify if it's methods will stuck in queue or will be called on object concurrently.
So depending on choosing architecture you can either relay on WCF ability to host single object which will have logic you described or you can go the way tried.
Links
http://msdn.microsoft.com/en-us/magazine/cc163590.aspx
http://msdn.microsoft.com/en-us/library/ms731193.aspx
A lock is fine here, but you should make your locker object static so the same object instance is used in the lock every time.
It does not matter how many cores you have - if you hold the lock on an object then any other threads that attempt to acquire the lock will wait until the lock is released.
A deadlock can only occur if you are acquiring multiple locks in different orders in different threads.
I suggest you read Joe Albahari's excellent free ebook