multithreading - VB.NET Event Handler as the producer of a multithreaded producer-consumer pattern -


the pattern below smells few reasons, purposes of question, let's focus on global variables , event handler:

dim objectqueue new blockingcollection(of object) dim objectqueuecancel new cancellationtokensource  sub main()     task.run(sub()                  if console.readkey.keychar() = "c" objectqueuecancel.cancel()              end sub)     dim t1 task = task.run(sub() nonblockingconsumer())     dim t2 task = task.run(sub() nonblockingproducer())     task.waitall(t1, t2)     objectqueuecancel.dispose()     console.writeline("press enter key exit.")     console.readline() end sub  private sub nonblockingproducer()     dim sourceobjects icollection(of object) = nothing 'sanitized stackoverflow     each sourceobject in sourceobjects         if sourceobject.isenabled             dim objecteventgenerator new objecteventgenerator(sourceobject)             addhandler objecteventgenerator.objectevent, addressof handler_objectevent             objecteventgenerator.enabled = true         end if         if objectqueue.isaddingcompleted exit     next sourceobject end sub  public sub handler_objectevent(byval sender object, byval e objecteventargs)     if not objectqueue.isaddingcompleted         if not e.eventexception nothing             environment.exitcode = -1         else             dim itemtoadd object = nothing             dim itemqueued boolean = false                             try                     itemqueued = objectqueue.tryadd(itemtoadd, 0, objectqueuecancel.token) 'todo tweak enqueue timeout                 catch ex operationcanceledexception                     objectqueue.completeadding()                     exit                 end try                 if itemqueued                     itemtoadd = nothing                 else                     thread.sleep(0)                 end if             loop while not itemqueued         end if     end if end sub 

the way of programmatically accessing objects in target use case through event listener, , while code executes has 2 pesky global variables. if define / dim blockingcollection , cancellationtokensource in main() sub, have pass them (i expect byref) event handler way of nonblockingproducer(). however, event handler's signature fixed, i.e. can't extend able pass variables in...

what "proper" way of refactoring eliminate global variables?


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -