|
I'd recommend adding that to the datasource of the grid, not the grid itself. Are you using SQL to load data in the grid?
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
I had the strangest problem today, and I did manage to solve it but I don't understand why it wont work out of the box.
So I created an Observable that is just a range:
Observable.Range(0, 15)
.SubscribeOn(Scheduler.Default)
.Select(x => Task.Run(()=>LongRunningTask(x,
CompletedOctavebandCalcualtions,
CalculatedValues),
CancellationToken.None).ConfigureAwait(true))
.Subscribe();
I have the LongRunning task as follows:
Random RandomTimeInterval = new Random();
public FreqValues LongRunningTask(double currentInteger, IProgress<double> ProgressBarIncrement, IProgress<FreqValues> CalcualtedValues)
{
FreqValues Result = new FreqValues();
Result.Frequency = currentInteger;
Result.Value = currentInteger - RandomTimeInterval.Next(0, 10000);
Thread.Sleep(RandomTimeInterval.Next(0, 3000));
Debug.WriteLine("Current integer:{1} on threadId:{0}", Thread.CurrentThread.ManagedThreadId, Result.Frequency.ToString());
ProgressBarIncrement.Report(1);
CalcualtedValues.Report(Result);
return Result;
}
Ï used the IProgress to update the UI on how many threads had completed. I have deliberately messed up the time each thread will take to be able to spot any mistakes. Updating the UI is straight forward:
Progress<double> CompletedOctavebandCalcualtions = new Progress<double>(s =>
{
pgbProgress.Value += s;
});
Progress<FreqValues> CalculatedValues = new Progress<FreqValues>(s =>
{
UnsortedCalcualtedValues.Add(s);
MyStrings.Append(s.Frequency.ToString() + " Hz with the Value: " + s.Value.ToString() + Environment.NewLine);
if (UnsortedCalcualtedValues.Count == NumberOfFrequencies)
{
txtText.Text = MyStrings.ToString();
}
});
What I don't understand at all is why I cant get the UI values to update if I put anything in the Subscribe. I will have to ObserveOnDispatcher of course, but that is easy:
Observable.Range(0, 15)
.SubscribeOn(Scheduler.Default)
.Select(x => Task.Run(()=>LongRunningTask(x,
CompletedOctavebandCalcualtions,
CalculatedValues),
CancellationToken.None).ContinueWith(e=>e.Result))
.ObserveOnDispatcher()
.Subscribe(evt=>
{
txtText.Text += evt.Result.Frequency.ToString();
}
);
The problem with that code is simply that the callback to the progress bar doesn't work, and the code inside the Subscribe will only execute once all the threads are completed. That the end result only shows after it is completed is fine for the text box, but I need to show the calculation progress. Can anyone tell me why It won't update?
|
|
|
|
|
|
I took my approch from this article: Async in 4.5: Enabling Progress and Cancellation in Async APIs | .NET Blog[^]
I did try to use the invoke as well, inside the Task call method. I would use the invoke method like this:
this.pgbProgress.Dispatcher.Invoke(DispatcherPriority.Normal,
new Action(() => { this.pgbProgress.Value += 1; }));
This is basically the WPF invoke method but unfortunately, it didn't change anything. The values didn't update until all the Rx tasks were done.
|
|
|
|
|
That article may be fine, it doesn't seem to focus on UI handling; for WinForms all Controls should be created and handled on exactly one thread, otherwise all anomalies are possible, and a temporary or permanent hangup is most likely to occur.
I trust the same holds true for WPF. Maybe your attempt failed to correct all cross-thread violations, or OTOH your code could have a second problem on top of the UI threading one.
|
|
|
|
|
Luc Pattyn wrote: That article may be fine, it doesn't seem to focus on UI handling; for WinForms all Controls should be created and handled on exactly one thread, otherwise all anomalies are possible, and a temporary or permanent hangup is most likely to occur.
That is one of the selling points of using Rx, the ease of switching between the UI thread and a background thread to ensure that the UI is responsive.Take the following example (you need the rx-main and rx-xaml NuGet packages to run the code)
var RxMouseMoveEvent = Observable.FromEventPattern<MouseEventArgs>(this, "MouseMove")
.Select(arg=>arg.EventArgs.GetPosition(this));
RxMouseMoveEvent
.ObserveOn(Scheduler.Default)
.Throttle(new TimeSpan(0, 0, 0, 0, 500))
.Select(xy => CalculatePointRelateThing(xy))
.ObserveOnDispatcher()
.Subscribe(evt =>
{
txtText.Text = evt.ToString();
});
The code does all calculation off the UI thread, so the UI doesn't hang up and remains responsive all the time. The problem was mixing this with the async Task calls seem to behave in a strange way.
Luc Pattyn wrote: Maybe your attempt failed to correct all cross-thread violations, or OTOH your code could have a second problem on top of the UI threading one.
That might be the case, but right now I'm confused and don't even know where to look for my mistake. I basically want to start several async processes in the off UI thread. Each time an async prosses finishes I want a notification sent to the subscriber together with the result of the calculation. In addition to this, I wanted to know when all the started tasks were done, in order to display the results in an orderly fashion. After all the async processes could finish async
I did manage to get it to work, but I felt that that was a dirty hack that I didn't like and was hoping to avoid using.
|
|
|
|
|
I figured it out now, turns out that the Task sends the Task instance to the Subscriber as soon as it is created, and not when it is completed, so:
.Subscribe(evt =>
{
if (!evt.IsCompleted)
Debug.WriteLine("Event Not completed");
else
Debug.WriteLine("Event completed");
pgbProgress.Value += 1;
MyStrings.Append(evt.Result.Frequency.ToString() + " Hz with the Value: " + evt.Result.Value.ToString() + Environment.NewLine);
},
() => {
txtText.Text += MyStrings.ToString();
}
);
This means that the subscribe thread on the UI is prosessing as it waits for all of the results to come in before it updates the UI.
|
|
|
|
|
Finally understood how to do this the proper way:
Observable.Range(0, 5)
.SubscribeOn(Scheduler.Default)
.SelectMany(x => Task.Run<FreqValues>(() => DoTaskWork(x), ctr.Token))
.ObserveOnDispatcher()
.Subscribe(args => {
pgbProgress.Value += 1;
txtText.Text += Environment.NewLine + args.Frequency.ToString();
},
() => {
txtText.Text += Environment.NewLine + "All done";
}
);
Trick was to use the SelectMany instead of the Select. This will return the T value from the Task<t> once any of the threads is completed.
|
|
|
|
|
Here's a behavior I have not seen before:
1. open a WinForms project
2. add a UserControl, put some controls on it, like a button
3. add a second UserControl, and set it to inherit from the first UserControl rather than 'UserControl
Now try to open the design-time view of the second UserControl: sometimes it's visible, and other times you get a message like this:Message 1 The designer could not be shown for this file because none of the classes within it can be designed. The designer inspected the following classes in the file:
BoolValidatingTextBox --- The base class 'March_15_ValidatingTextBox2.ValidatingTextBoxBase3<system.boolean>' could not be loaded. Ensure the assembly has been referenced and that all projects have been built. 0 0 The same project producing the error, when opened in VS 2015, shows the inheriting UserControls properly in the design-time view.
Even though the inheriting UseControls will not display at design-time, they are fully functional: you can drag-drop them onto a Form, and see the correct design-time view of the Form.
Anyone else had this head-ache ? I've examined the various .config and .csproj files looking for some clue to this, but found nothing.
«The truth is a snare: you cannot have it, without being caught. You cannot have the truth in such a way that you catch it, but only in such a way that it catches you.» Soren Kierkegaard
|
|
|
|
|
Um...works for me, but on 2013.
Microsoft Visual Studio Community 2013
Version 12.0.31101.00 Update 4
Microsoft .NET Framework
Version 4.6.01038
Installed Version: Professional
I did manage to cause the same error, but a quick build got rid of it (which makes sense).
And once it's gone, it's gone...
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
Thanks, Griff, I'm using:
Microsoft Visual Studio Professional 2013
Version 12.0.40629.00 Update 5
Microsoft .NET Framework
Version 4.6.01055
Installed Version: Professional
I am compiling the current project with .NET 4.5. The VS 2015 version I have is, of course, the Community Edition. I've tried all the flavors of cleaning and re-building and building. The setting I am using for the build are all very standard for me (the current machine is 64 bit): prefer 32 bit, Any CPU, Define Debug, Define trace both checked.
Since I was able to repo the unexpected behavior with a very simple test case, I discount the idea that the fact the current project uses a "base" UserControl with a generic parameter, and the inheritors specify the parameter type, is leading to the unexpected behavior. And, no sign of this problem in VS 2015. Like this:
namespace ANameSpace
{
[ToolboxItem(false)]
public partial class ValidatingBase<T> : UserControl
{
public ValidatingBase()
{
InitializeComponent();
namespace ANameSpace
{
[ToolboxItem(true)]
public partial class PersonValidator : ValidatingBase<Person>
{
public PersonValidator()
{
InitializeComponent();
As I said, the only issue is the lack of design-time UI view; the UserControls appear in the ToolBox, can be drag-dropped onto a Form where they appear as expected and the solution ... works
Always something new ...
cheers, Bill
«The truth is a snare: you cannot have it, without being caught. You cannot have the truth in such a way that you catch it, but only in such a way that it catches you.» Soren Kierkegaard
|
|
|
|
|
write a console application in c# which contain a list of doctors and a list of departments. in this application a department can contain
many number of doctors but any doctor can a part of only one department. and make application flexible to add and remove doctors and departments.
|
|
|
|
|
Ok, you have my permission to proceed.
Hint: This is not a question.
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
|
|
|
|
|
|
Ok you know what you have to do.
Now, you can start to work.
Patrice
“Everything should be made as simple as possible, but no simpler.” Albert Einstein
|
|
|
|
|
Pls, how can I sort records on a datagrid using d fourth column. Then generate serial numbers in d fifth column after sorting. view my code sample
<asp:gridview id="grid" runat="server" autogeneratecolumns="False"
="" headerstyle-bordercolor="#996633" width="98%" allowpaging="True" backcolor="White" bordercolor="#999999" borderstyle="Solid" borderwidth="1px" cellpadding="3" forecolor="Black" onpageindexchanging="grid_PageIndexChanging" pagesize="20" allowsorting="True" onrowediting="grid_RowEditing" onrowupdating="grid_RowUpdating">
<alternatingrowstyle backcolor="#CCCCCC">
<columns>
<asp:boundfield headertext="Reg. No"
="" controlstyle-width="10%" datafield="AdmNo" sortexpression="AdmNo">
<controlstyle width="20%">
<itemstyle width="10%">
<asp:boundfield headertext="Ass(1)"
="" controlstyle-width="10%" datafield="Ass1" sortexpression="Ass1">
<controlstyle width="15%">
<itemstyle width="10%">
<asp:boundfield headertext="Ass(2)"
="" controlstyle-width="10%" datafield="Ass2" sortexpression="Ass2">
<controlstyle width="15%">
<itemstyle width="10%">
<asp:boundfield headertext="Test(1)"
="" controlstyle-width="15%" datafield="Test1" sortexpression="Test1">
<controlstyle width="15%">
<ItemStyle Width="10%" />
</asp:BoundField>
<asp:BoundField HeaderText ="Test(2)"
ControlStyle-Width = "5%" DataField="Test2" SortExpression="Test2" >
<controlstyle width="5%">
<itemstyle width="10%">
<asp:boundfield headertext="Exams"
="" controlstyle-width="35%" datafield="Exams" sortexpression="Exams">
<controlstyle width="15%">
<itemstyle width="10%">
<asp:boundfield headertext="Total"
="" controlstyle-width="5%" datafield="Total" sortexpression="Total">
<controlstyle width="5%">
<itemstyle width="5%">
<asp:boundfield headertext="Grade"
="" controlstyle-width="5%" datafield="Grade" sortexpression="Grade">
<controlstyle width="5%">
<itemstyle width="10%">
<asp:boundfield headertext="Remark"
="" controlstyle-width="5%" datafield="Remark" sortexpression="Remark">
<controlstyle width="5%">
<itemstyle width="10%">
<asp:boundfield headertext="Position"
="" controlstyle-width="5%" datafield="ClassPosition">
<controlstyle width="5%">
<itemstyle width="10%">
<asp:commandfield showeditbutton="True" showcancelbutton="False"
="" buttontype="Button">
<FooterStyle BackColor="#CCCCCC" />
<headerstyle bordercolor="#996633" backcolor="Black" forecolor="White" font-bold="True">
<pagerstyle backcolor="#990000" forecolor="White" horizontalalign="Center">
<selectedrowstyle backcolor="#000099" font-bold="True" forecolor="White">
<sorteddescendingcellstyle backcolor="#CAC9C9">
-- modified 21-Mar-16 8:30am.
|
|
|
|
|
Don't try and do it via the datagrid, do it to the collection you used as the datasource. How that works depends on the collection type.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Back in Feb. 2016 I posted a How create a parallel task to call the same method -- Solution 2[^]
I'm not fishing for Reputation Points, but since I'm relatively new with Rx, I'm wondering if there's a better way to do this using Rx.
Since the question didn't originally reference/tag Rx, it might not have attracted the notice of the Rx folks. Nor is there any other way to tag the solution with Rx so you other Rx users would see (and comment on) it.
If this is inappropriate, please let me know and I'll remove it.
"Fairy tales do not tell children the dragons exist. Children already know that dragons exist. Fairy tales tell children the dragons can be killed."
- G.K. Chesterton
|
|
|
|
|
|
Hmm, your question seems more and more important the deeper I look. The previous post is ok, it works and shows some nice things. But I read this post here:
StartNew is Dangerous[^]
And realized that I could probably do it a bit simpler with this call instead exchanging the default values at demand of course:
Observable.Range(0, 10).
Select(e => (Task.Factory.StartNew(() => DoWork(e),
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default)))
.ObserveOnDispatcher()
.Subscribe(evt =>
{
});
But supposed I only wanted 5 parallel processes to run at the same time? How could I do that? I also seem to get the values once everyone is finished, and I'm currently not entirely sure what that is the case either.
I could also use the Observable.Start(()=>DoWork(e)) but the result in the subscriber seemed unusable to me, perhaps I mistook something here?
|
|
|
|
|
Your comments don't seem to be related to my code. How did you intend for them to apply?
Why did you refer to StartNew ? I didn't use that. I used Task.Run() .
In the original question the point was to cancel any tasks once any one had returned true.
My code accomplishes that.
I didn't use the .ToObservable() (that you referenced in your previous comment) on the Task s since, in the current Rx, Task and Task<T> can be used where IObservable<Unit> and IObservable<T> can.
I don't know about how you could limit to 5 parallel Task s as you asked...
"Fairy tales do not tell children the dragons exist. Children already know that dragons exist. Fairy tales tell children the dragons can be killed."
- G.K. Chesterton
|
|
|
|
|
I misread the question a little, I thought he also wanted to stop the calculation with a UI event also. I saw this question mainly as a cross thread communication issue.
The reason I liked the .ToObservable() is that I could easily move the thread initialization off the UI by calling .SubscribeOn(Scheduler.Default) , I always like to do that as soon as possible. But I guess it's not going to make a big deal of difference.
As for my question, I realized that restricting the number of new threads is not necessary, as the Run.Task or TaskFactory.StartNew manages that for me (They could work in the same way with proper initialization). I though the methods always started a new thread, but that is not the case.
Guess I need to drink a little more Sorry for my confusion here
|
|
|
|
|
Since my solution used a CancellationToken the UI should be able to use that to stop all of the calculations that way also. The CancellationTokenSource would need to be "exposed", or a method to .Cancel() the token source would need to be provided.
"Fairy tales do not tell children the dragons exist. Children already know that dragons exist. Fairy tales tell children the dragons can be killed."
- G.K. Chesterton
|
|
|
|
|
I just saw your Rx post on updating the UI, etc. and realized that you may have been using this thread to "prompt" me to look at that one...
"Fairy tales do not tell children the dragons exist. Children already know that dragons exist. Fairy tales tell children the dragons can be killed."
- G.K. Chesterton
|
|
|
|
|
I have a for loop that outputs a sequence of numbers.It checks to see if each number from 100 to 10000 is odd or even. If it is odd, it appends the number to a stringbuilder object.
when the loop is done checking for odd numbers, it converts the stringbuilder object to a string object and prints it out.
Below is a code snippet similar to my actual code
class Program
{
static void Main(string[] args)
{
AllNumbers number = new AllNumbers();
number.ShowOddNumbers();
Console.ReadLine();
}
}
publuic class AllNumbers()
{
public void ShowOddNumbers()
{
StringBuilder OddNumbers = new StringBuilder();
StringBuilder comma = new StringBuilder(", ");
for (int i = 100; i <= 10000; i++)
{
if (IsOddNumber(i))
{
OddNumbers.Append(i).Append(comma);
}
}
Console.Write(Odd.ToString().TrimEnd(' ').TrimEnd(','));
}
}
The problem I am having is that I cannot make the WriteLine() function printout only X number of odd numbers per line. How do I make each line have say 10 numbers max separated by commas? Thanks in advance.
modified 18-Mar-16 18:42pm.
|
|
|
|
|