As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I know the technique about UI thread updating from another thread.
So I have these two methods/techniques, which one should I use?
Using Task:
var uiTask = Task.Factory.StartNew(() => {
// change something on ui thread
var action = theActionOnUiThread;
if (action != null) {
action();
}
}, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
Using Dispatcher:
Dispatcher.CurrentDispatcher.BeginInvoke(
new Action(() => {
// change something on ui thread
var action = theActionOnUiThread;
if (action != null) {
action();
}
}));
From a technical point of view I doubt there is a 'best' here. however I'd go with the dispatcher approach:
it makes your intent more clear, namely that you want to get something done on the main ui thread
you don't need to boter with all the task factory options
Dispatcher makes it easier to hide everything behind an interface (1) allowing easy dependency injection and unit testing
(1) see here for example
TaskScheduler.FromCurrentSynchronizationContext() does not guarantee returning you a TaskScheduler for the UI thread.
In fact it can sometimes return null, although these cases are rare and generally involve spinning up your own dispatcher in a native app (for example the WIX bootstrapper).
So I'd say it's safer to use the dispatcher version.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm starting using ReactiveUI in some projects; I still have some difficult to understand some core concepts and I don't know how to manage some common scenario, what are best practices.
Suppose I created a TextEditor which expose a TextChanged event. I manage to create an observable named "CanSave" attached to this event which emit true when user write something;
Now I can use "CanSave" as "canexecute" property of a Save command. This works but, when user click Save, "CanSave" should now emit false because user already saved his work!
How is supposed to manage situations like this? I figured out to create a CanSave settable property and subscribe it to changed event, then observe CanSave property .. is this the correct way?
You're nearly there, or maybe your terminology and description is misleading me.
You need some sort of an Iobservable IsDirty ( or CanSave ) which you can use as a canexecute.
This should be true when a significant change has been made but not saved.
You want to observe TextChanged and set IsDirty to true when that is raised. Maybe also checking something significant happened.
Change it to false when the user saves.
If you somehow make or wrap your IsDirty as an IoBservable you can then just pass it in a factory method like ReactiveCommand.CreateFrom.... for a reactive command.
var command = ReactiveCommand.CreateFromTask(LogOnAsync, IsDirty);
You could separate stuff by putting say length in other observables. In which case you'd want to build a canexecute that observes multiple observables using WhenAnyValue.
https://www.reactiveui.net/docs/handbook/commands/
A common preference is to work with a property. You then use observable as property helper
The docs tell you to work this way.
https://www.reactiveui.net/docs/handbook/observable-as-property-helper/
https://www.reactiveui.net/docs/guidelines/framework/prefer-oaph-over-properties
public class RepositoryViewModel : ReactiveObject
{
public RepositoryViewModel()
{
canDoIt = this.WhenAny(x => x.StuffFetched, y => y.OtherStuffNotBusy, (x, y) => x && y)
.ToProperty(this, x => x.CanDoIt);
}
readonly ObservableAsPropertyHelper<bool> canDoIt;
public bool CanDoIt
{
get { return canDoIt.Value; }
}
}
If you think about it, CanDoIt above is fairly similar to what you'd probably want.
Because you'll also want to guard your commands using something like IsBusy so the user can't hit save ( or anything time consuming ) then immediately try to do something else like hit save again whilst it's still doing it's thing.
In my opinion, reactiveui is pretty clever stuff.
But.
You're paying a lot for that functionality in terms of a learning curve and arguably a counter intuitive way of doing things.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I'm trying to implement an autocomplete algorithm for a programming language. I want it to be context aware, meaning that suggestions must appear relative to the statement the user is currently typing.
What is the best way to go around this? What algorithms should I be looking into?
You do not actually need to parse the language to do this.
Assuming you have a list of valid symbols you need only choose the most likely completions when the user presses the autocomplete key (say, TAB, eg). You can weight the symbols by their frequency in the code. You can also weight by symbol type, giving more weight to variable names than reserved words. For example, if the user types "th[TAB]" and they have a variable named "themes" which appears 50 times, that might be the top completion, with the reserved word "then" perhaps being 2nd.
To generate the frequency weighting you need to count the number of times each symbol appears in the code. This can be done using a standard string search algorithm.
If you do have a parser, you can do more fancy things. For example, if you determine all the methods of a class and the user enters the symbol for an instance of a class followed by a period, you can automatically display a list of the methods, because those are the only valid possibilities.
BTW: To build the symbol list will depend on the language. For example, if it is Java, you can use the built-in introspection methods to identify all the defined symbols.
You need a state machine that recognizes the grammar of your language. Additionally, the state transitions should be weighted according to their probability.
If the state of your engine is at public static, the weight of the state transition class could be higher than that of abstract. This would be necessary to display a practical number of options as suggestions.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Recently I had an interesting conversation with a fellow developer who told me that every time you write a "try" it is mandatory to provide a "catch". He could not explain why this rule. He told me that it was a principle of good programming. Why this rule?
For your information I'm not agree with him. I think that sometimes you could write a "try" block with only a "finally" block. But it's true that I think if you write a "catch" you must do something in your catch. Never just re-throw the error.
You're right : you don't need to write a catch clause if you don't know what to do with the exception and just want to ensure your finally clause is executed.
It's bad practice to add a catch clause just to rethrow the exception.
As an aside, to illustrate that catch and finally are in fact related to two different (admittedly not foreign) problems, note that some languages use a different construct for the catching of exception and to ensure some code (usually resource release) is executed. Go use defer for example.
In most applications try/finally constructs heavily outnumber try/catch constructs.
Because it's much more common to have resources to clean up than it is to receive an exception you know how to handle.
However try/finally is nearly always replaceable by using in C#, so in C# your developer might have a point in that case; but it most definitely isn't a "a principle of good programming".
try
{
...
}
finally
{
...
}
Gives you the opportunity to execute code in the finally block that would otherwise get missed if an exception were thrown in the try block.
You only need to add a catch block if you have something specific to do when an exception occurs.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Execute a WebRequest in a Background thread while UI Thread is blocked
Check out this code:
Thread t = new Thread((a) =>
{
var client = new WebClient();
client.DownloadStringAsync(new Uri("http://www.google.com"));
bool pointB = true;
});
t.Start();
t.Join(10000);
When this is run on the UI thread in Silverlight, even though DownloadStringAsync() is called quickly, pointB will not be reached until after the Join() times out. This means DownloadStringAsync() must somehow require the UI thread to do its work. Note: this has nothing to do with the callback to DownloadString. I know that WebClient's callbacks happen on the UI thread (see here: Silverlight Background Thread using WebClient).
The behavior of my code seems to indicate that the async invoke method itself (DownloadStringAsync()) also requires the UI thread. Is that right? And if so, why? I also want to note this same behavior is exhibited when using HttpWebRequest.BeginGetResponse()
Edit: to make things crystal clear, the order of operations I see when I step through this code is
t.Start()
t.Join(10000);
var client = new WebClient();
client.DownloadStringAsync(new Uri("http://www.google.com"));
(... Join() timeout)
bool pointB = true;
Alright, I think I figured out the answer after a little more digging. It does seem indeed that all network code is ultimately run on the UI thread:
http://nondestructiveme.com/2010/11/23/silverlight-and-networking-the-ui-thread/
The good news is it seems Microsoft fixed this "bug", as you might be justified in calling it, in Silverlight 5:
http://msdn.microsoft.com/en-us/library/gg986857(VS.95).aspx
(At the bottom of the page under Performance Improvements:
"Reduced network latency by using a background thread for networking. This is helpful for scenarios that use client HTTP web requests.")
I'll edit this answer once I test my code on Silverlight 5 to see if it indeed fixed the issue.
Edit: Built against Silverlight 5 and I'm still having the same problem. I think it's time for me to give up trying to block the UI thread at all...
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Structs interface and Hiding members in a C struct discusses various ways in accessing /modifying members.
What would be pros/cons of using:
Opaque handle to struct and setters/getters
Accessing members directly
foo.value(&foo, value) functions (like C++ class methods)
Separate header files for same struct exposing public members for client and all members internally
In my case, I'm doing OOP in C and all my structs hold a list of properties (id, name, desc, ...). I need to track changes so that changed status could be transmitted over network. The best way, as I see it, would be to transmit the delta (changes between individual members) and not retransmitting the whole struct.
Thank you