C# - .NET Async Lambda-expressions?
Apr 20, 2012
Async Sub like this: Dim f As Func(Of Task) = Async Sub() End Sub Produces compiler error: error BC36670: Nested sub does not have a signature that is compatible with delegate 'System.Func(Of System.Threading.Tasks.Task)'.Equivalent C# code compiles fine:
Func<Task> f = async () => { };Rewriting Async Sub into Async Function make code works.
Why does Async Sub() is not convertible to delegate types with return value of type Task?
View 1 Replies
ADVERTISEMENT
Nov 11, 2009
I see lambda expressions have become a very useful tool at some points in the language. I've been using them a lot and most of the time they fit really nice and make the code shorter and perhaps clearer.
Now.. I've seen some , I would say excessive use of them. Some people like them so much that try to use them everywhere they can.. Some times the C# code looks like a functional language. Other factors against are the cost using reflection by lambda and that not friendly to debugging.I would like to hear opinions about how good and how code clear it is to use more or less the lambda expressions. (this is not the better example, but let's say it was the trigger)I was writing the following code. The use of the delegate { return null; } helps me avoid having to ask if the event is null or not every time I have to use it.
public delegate ContactCellInfo.Guest AddGuest();
public event AddGuest GuestRequest = delegate { return null;}
Im using resharper and the wise resharper( even it some times literaly eats the memory) made me the following suggestion
public delegate ContactCellInfo.Guest AddGuest();
public event AddGuest GuestRequest = () => null;
At my point of view the code using the delegate looks clearer. I am not against the Lamdba expression just would like to hear some advices on how and when to use them.
View 1 Replies
Jan 20, 2010
Functionally, is there any difference (apart from syntax onbviously) between lambda expressions in C# and VB.Net?EDIT: following up on CraigTP's answer: any references to the situation in .Net 4?EDIT: I'm asking because I'm used to C#, but for a next project the customer asks VB.Net. We're not a priori against that. We realize that most language constructs are supported in both languages. However, we're particularly fond of the way C# implements lambda expressions. We would like to have an overview of the differences with VB.Net
EDIT: accepted CraigTP's answer for pointing out what I currently consider the most important difference.
So to summarize: VB.Net 9 does not support multiline statements in a lambda expression, and a lambda must always return a value. Both of these issues are addressed in VB.Net 10
View 5 Replies
Jul 4, 2010
how to convert this code to VB.net, can anybody help?
public static readonly DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached(
"Command",
[code]...
View 1 Replies
Feb 3, 2012
I have a List(of T) where T has a property that is a list of checkboxes, what I need is a Lambda expression that will count all the checked checkboxes in the list. I tried with:
[Code]...
View 5 Replies
Jul 19, 2011
I just came across a bug in NHibernate which happens to already be raised: [url] I'm not sure if this applies to anything else other than enums but when using a Lambda from VB, it looks different to the same Lambda from C#.
C#:
Where(x => x.Status == EmployeeStatus.Active)
VB
Where(Function(x) x.Status = EmployeeStatus.Active)
They are the same as far as I'm aware? (My VB isn't great) If I put a break point on the same line of code, where the above code is passed into. In C# I get: On the same line when VB version is passed in, I get: Is this something I'm doing wrong? Is the result's the same, just displayed different between C#/VB?
Edit: Ok so they are displayed different, but they can't be the same because NHibernate cannot handle it. The C# version is handled perfectly fine by NHibernate, the VB version resolves in the following exception being thrown: [Code]
View 3 Replies
Jul 25, 2011
I have an issue with building a project using the MSBuild (ver 4) from the command line when declaring lambda expression like this:
Private Sub Foo(ByVal s As String)
Dim WL = Sub(str As String)
If Not String.IsNullOrEmpty(str) Then[code]......
View 1 Replies
Mar 6, 2009
I'm trying to expand my programming horizons, and LINQ and Lambda Expressions have popped up as some apparently very important topics. As I began reading articles on Lambda Expressions, it appears that Lambda Expressions are built heavily on the concept of Delegates. As I began reading articles on Delegates, it appears that Delegates are built heavily on the concept of callback functions. As I began reading articles on callback functions, .[code]Can anyone out there give me a simple, clear, concise definition of callback functions? Do I need to learn C or C++ to fully understand these concepts? Maybe a better question is: What do I need to know to be able to understand Delegates (they've always somewhat mystified me) and LINQ/Lambda Expressions (I haven't looked into these too much, but they're mystifying, too)?I don't mind doing research, but google searches are giving me way too much information.
View 4 Replies
Jul 7, 2010
what are delegates?How are the lambda expressions related to the delegates?
reading the msdn about the delegates is really confusing me ;so i need a start off from here before moving on to the msdn.
View 27 Replies
Jul 1, 2011
To streamline code, I increasingly rely on lambda expressions. But I may have hit against the wall in the attempt of removing an event handler set by a lambda expression. This really eludes me. The code below shows two samples: Alt1 uses a plain lambda expression as delegate and works fine: the object size increases as the numeric control varies. However, the drawback is that the handler cannot be removed:
RemoveHandler Me.upDnScale.ValueChanged, Sub(sender As Object, e As Object) ScaleObject1(sender, e, objTgt)
According to this MSDN article, a variable should be used to set/remove lambda based handlers. Alt2 shows a couple of attempts, but none works.
[Code]...
View 1 Replies
Feb 22, 2010
I have a type lets call it "MyType". I have a List(Of MyType). Here is what i'm doing: MyList.Sum(Function(x) x.MyFieldToTotal) "MyFieldToTotal" is a decimal. For the life of me i can't figure out why x above is an object rather than a type of "MyType". Shouldn't Type Inferencing be working in this case? Even in intellisense i get "selector as System.Func(Of MyType) as Decimal"
[Code]...
View 1 Replies
May 21, 2012
Currently I am searching through my list to find Customers that match on Address.
I need to match on both address and city. How do I rewrite my lambda Expression to match both criteria?
CustomerList.FindAll(Function(c) c.Address = addressToMatch)
View 1 Replies
Jul 2, 2011
How to remove a handler set up by a lambda expression? According to this MSDN article, lambda expression should be assigned to variables which should be used to define handler operators. So far, I have used lambda expessions w/o variables.
For instance, the following works:
Private Sub ScaleObjectInit1(ByVal objSrc As NumericUpDown, ByVal objTgt As FrameworkElement) ...
AddHandler Me.upDnScale.ValueChanged, Sub (sender As Object, e As Object) ScaleObject1 (sender, e, objTgt)
End Sub
Private Sub ScaleObject1(ByVal sender As Object, ByVal e As Object, ByVal objTgt As FrameworkElement)
[Code] .....
View 3 Replies
Jun 30, 2011
Can someone who is using a 64 bit machine help me pintpoint this crash to either the VS2010 IDE itself or one of the plugins I have installed?
It's the code fragment below. When I copy & paste it into the Main() function of a new VB.Net console app on my Win7 64 bit machine, the VS IDE crashes and dies onthe spot, every time I try it.
Doing exactly the same on a 32 bit XP machine, nothing abnormal happens.
The 64 bit machine does have some IDE plug-ins installed, the biggest of which is DevExpress (the free version), so i think either one of those or the fact that the IDE is running on 64 bit must be the culprit.
This is the code. The static variable can also be made a module-level variable, with the same result.
View 2 Replies
Nov 16, 2009
I'm still trying to get my head around the whole "Lambda Expressions" thing.
Can anyone here give me an example ordering by multiple columns using VB.Net and Linq-to-SQL using a lambda expression?
Here is my existing code, which returns an ordered list using a single-column to order the results:
Return _dbContext.WebCategories.OrderBy(Function(c As WebCategory) c.DisplayOrder).ToList
Note: The WebCategory object has a child WebPage object (based on a foreign key). I'd like to order by WebPage.DisplayOrder first, then by WebCategory.DisplayOrder.
I tried chaining the order bys, like below, and though it compiled and ran, it didn't seem to return the data in the order I wanted.
Return _dbContext.WebCategories.OrderBy(Function(c As WebCategory) c.DisplayOrder).OrderBy(Function(c As WebCategory) c.WebPage.DisplayOrder).ToList
View 2 Replies
Mar 16, 2009
I have an untyped dataset returned from my WebService. The user wants to dynamically construct a query referencing tables and columns and specifying values to test for.I have looked at Lambda Expressions and the Expressions.Expression Namespace. I think these provide the answer I'm looking for, but I'm not certain how to go about contructing the linq expressions to extract the datarows I'm looking for.
I plan on limiting the result to one datatable that the query will result in and i"ll provide the joins from the user's constructs.For a simple example I have a DataTable with (n) rows called "Table", and in it there is a computed column called "b_IsActive" that has the expression "Convert(IsActive, 'System.Boolean')". The user wants to retrieve all rows in "Table" where field "b_IsActive" is true.
View 5 Replies
May 20, 2009
I'm looking for an advanced level VB.NET book which covers LINQ and Lambda Expressions.Generally I read C# .NET books due to lack of good VB.NET books when it comes to generic .NET Framework related subjects. However Lambda and LINQ is quite different in C# and VB.NET I'm looking for an advanced level VB.NET book on this subjec
View 1 Replies
Jun 3, 2010
I'm trying to write a 'developer friendly' wrapper for the Windows API EnumWindows - the problem is that the API uses a callback function that gets invoked on another thread, where as I want my wrapper function to simplify this and make it more useful by working like any other normal synchronous function and just returning a value.
Now if the API just called the callback once that would be fine, as I would just call the API and make the wrapper function wait until it got a signal from the callback function telling it to continue... but the API calls the callback function over 100 times (once for every window handle that exists). The biggest problem is that there is nothing that indicates that any particular call to this callback function is the last one, so my wrapper function has no idea when it is safe to continue and return the list of window handles to the caller.
The only solution I could think of is to do this:
1. The wrapper function calls the API and starts a timer that waits 2 seconds before it raises the Elapsed event. The wrapper function then pauses until it receives a signal (ManualResetEvent)
2. Each time the callback function is raised by the API on a different thread, it stops the timer (so this is before the 2 seconds have elapsed), adds the current window handle that was passed in by the API to the list of handles, then starts the timer again.
3. If the timer reaches its 2 second interval then it is assumed that we are at the end of the windows because otherwise the callback would have stopped the timer. So the timer's Elapsed event handler is what signals the original thread (that the wrapper function is executing on) to continue as we now have a complete list of windows to return.
This works fine and does exactly what I want... but I dont like it.
I dont like forcing the caller to wait an extra 2 seconds after the API has done its last callback but more importantly I dont like assuming that the API will never take longer than 2 seconds between callbacks. In reality on my PC it is never anywhere near that long between callbacks, it is something like 200 miliseconds, but I have no idea how long it would be on a slower PC and I want this to be completely reliable.
[URL]
View 14 Replies
Jun 21, 2011
Im hearing about this, can someone explain it to me or please show some basic code of Lambda with explanation.
View 2 Replies
Dec 14, 2009
Is it possible to shorten the following function to a lambda expression?Or (to do the trick by myself) what is the best and most understandable for beginners tutorial for lambda in vb.net?[code]
View 2 Replies
Jul 15, 2010
I have two methods on the page. One AddMessageToInboxOutbox(params[]) and other one SendNewMessageMail(params[]).
Once user sends an message to other other first message is added to DB and then sent to recipient's email. Sometimes SMTP is heavy loaded and it takes up to 5 seconds to get answer from it. I want to enclose SendNewMessageMail(params[]) with async call using other thread or something. I have never done that.
How do i perform this action right in ASP.NET?
View 2 Replies
Nov 3, 2011
[Code]...
In my scenario the Button_Click is a command delegate in the VM, and the Thread.Sleep is some long-running process (about 2-10 seconds). I want, that when the user calls the command, it should immediately update the UI disabling the button so the user cannot execute it while it's running, then execute that operation, then, when operation completed, unblock the button.
[Code]...
View 3 Replies
Jun 12, 2009
I have a bunch of operations that need to be executed simultaneously. For this I'm using the thread pool to execute the tasks. I'd like to know if it's possible to consume some sort of Async Callback (similar to BackgroundWorker.DoWorkComplete) when each thread is finished. The reasoning behind this is that I have a windows service running that uses IPC to update a GUI and I need to know the time at which each specific thread finishes I've used background workers to do a set of tasks and they work perfectly, however, they take longer than I would like. I've timed the execution on my BGW method for a designated number of said tasks and it took 27 seconds, and the same set of tasks takes 4 seconds using the threadpool method. I've also tried using managed threads, to the same effect as the background workers.
View 5 Replies
Oct 1, 2011
I think this is a simple question for you, but I don't understand other cases of webRequests, so I asked here: How can I make this webRequest asynchronous?
Dim sBuffer As String
Dim oRequest As WebRequest = WebRequest.Create(url)
oRequest.Method = "GET"
Dim oResponse As WebResponse = oRequest.GetResponse()
Dim oStream As New StreamReader(oResponse.GetResponseStream())
[Code] .....
View 1 Replies
Jul 15, 2011
Relevant to Silverlight 5 / Async CTP
I want to create an asynchronous function that initiates a layout update and then Awaits for the layout update to complete. Something like:
Private Async Function UpdateLayoutRoot() As Task
LayoutRoot.UpdateLayout()
Await LayoutRoot.LayoutUpdated <--- (NOT valid but shows desired outcome)
End Function
How can this be done? More generally, how can you use Await to wait for existing events?
View 2 Replies
Mar 31, 2011
I have some code that iterates a few 100 urls and requests the data from the web.It looks something like this
for each url in urls
Dim hwr = CType(WebRequest.Create(url), HttpWebRequest)
Dim rq = New ReqArgs
[code]....
How come the BeginGetresponse line takes about 2-3 seconds to complete before going to dim a=1?. Actually I debugged and I see that the FinishWebRequest procedure runs completely before the Dim a=1 is reached.So is this async?I'm not earning any time by using the async. am I? Or is there a different way to do this?The point is that the main sub should fire off 300 requests and return control to the UI, then the FinishWebRequest should process them slowly on its own thread and own time , as the requests come in.How do I do that?Btw, the main sub is running in a BackgroundWorker, but I checked with out the BackgroundWorker and the problem is the same?
View 1 Replies
Jun 14, 2012
I have a WPF application in which i have to do a long running task (basically reading from network). Just to give you a snapshot I am doing the following thing on button click
Dim t As Task(Of String) = Task.Factory.StartNew(Of String)(Function()
'Thread.sleep is simulating long running task that will make UI unresponsive
Thread.Sleep(10000)
[Code].....
I cannot use Event based async methodology because the reading API actually exist in a dll which i refer in my program, that contains a function Public function ReadFromNetwork() as String. This API is making an async call to network to read a long string and return to UI. So, in short i m doing TextBlock1.Text = ExternalDll.ReadFromNetwork().
but the problem is that even if i use Task asynchrony, the UI is still unresponsive.
View 3 Replies
Nov 24, 2011
I've run into a bit of a problem using Async ping. Basically, I want to ping computers in the list before I run the next bit of my program. The computers who I can ping are added to a list and that is used in a background worker. Trouble is can't seem to work out how to wait until after pinging ALL computers in the list, either successful or timed-out. Is there something a long the lines of 'If Async Ping is running'?
Private Sub pingCompleted(ByVal sender As Object, ByVal e As System.Net.NetworkInformation.PingCompletedEventArgs)
If e.Reply.Status = Net.NetworkInformation.IPStatus.Success Then
complist.Add(e.UserState)
Else
'do nothing
End If
End Sub
I need the next bit to wait because if 'complist' is changed while it's being used I get collection errors.
View 7 Replies
Dec 21, 2009
I am working on moving a project from VB6 to VB 2008 Express. [Code] When I connect to mysql db in VB6, I connect using adAsynConnect. This way, I have a "Loading..." animation display while a connection is attempted. Is there a way to do this in 2008 Express? Or something similar I could read up on?
View 4 Replies
Jul 25, 2011
I'm using vb .net 2008 with 3.5 framework. (the following 2 classes are put in a DLL that i import in a main application)
Server class:
Code:
Imports System.Xml
Imports System.Net.Sockets
Imports System.Text
Imports System.Net
[code]....
Basically in my main application i am instantiating the client class from this dll, as well as the server one. On the client form i got a "send data" (SendFISA sub) and a "connect" button. After connecting the client and clicking on the "send data" i am sending to the server a string formed of some information created when instantiating the client class from the dll (i can't make that type of data public, but i'm just using a constructor to assign values to a class object, nothing special).
Now, when the server receives the data sent by "send data" button click it responds with "PKG_SENT" corresponding to the "FISASENT" string terminator(in the module) of the string that was sent. The "WRONG_MSG" constant is for when the string terminator is different from the 2 from above.
On the local disk, if the server cannot be reached, the client saves an xml file with this data. In the dll i made a timer that ticks every 5 seconds and checks to see if there is any xml file on the disk and sends it to the server if the connection is ok (trimiteXML sub). The server would respond with "XML_SENT" corresponding to the string terminator "XMLSENT"(in the module) appended to the read string from the xml file. After the file is sent it is deleted from the local dir.
The problem occurs when i click "send data" AND there are XML files to be sent from the disk. I believe they are interpreted by the server somehow at the same time because the message is neither "PKG_SENT" nor "XML_SENT", but it becomes a combination of the "WRONG_MSG_TYPE" and "XML_SENT", "XML_SENTG_TYPE". I have no idea why this is happening and i basically want the socket to wait with sending the files from the disks until the "send data" finishes.
View 9 Replies