Sending Arguments To Background Worker? - c#

Let's say I want to sent an int parameter to a background worker, how can this be accomplished?
private void worker_DoWork(object sender, DoWorkEventArgs e) {
}
I know when this is worker.RunWorkerAsync();, I don't understand how to define in worker_DoWork that it should take an int parameter.

You start it like this:
int value = 123;
bgw1.RunWorkerAsync(argument: value); // the int will be boxed
and then
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
int value = (int) e.Argument; // the 'argument' parameter resurfaces here
...
// and to transport a result back to the main thread
double result = 0.1 * value;
e.Result = result;
}
// the Completed handler should follow this pattern
// for Error and (optionally) Cancellation handling
private void worker_Completed(object sender, RunWorkerCompletedEventArgs e)
{
// check error, check cancel, then use result
if (e.Error != null)
{
// handle the error
}
else if (e.Cancelled)
{
// handle cancellation
}
else
{
double result = (double) e.Result;
// use it on the UI thread
}
// general cleanup code, runs when there was an error or not.
}

Even though this is an already answered question, I'd leave another option that IMO is a lot easier to read:
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (obj, e) => WorkerDoWork(value, text);
worker.RunWorkerAsync();
And on the handler method:
private void WorkerDoWork(int value, string text) {
...
}

You can pass multiple arguments like this.
List<object> arguments = new List<object>();
arguments.Add("first"); //argument 1
arguments.Add(new Object()); //argument 2
// ...
arguments.Add(10); //argument n
backgroundWorker.RunWorkerAsync(arguments);
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
List<object> genericlist = e.Argument as List<object>;
//extract your multiple arguments from
//this list and cast them and use them.
}

You can use the DoWorkEventArgs.Argument property.
A full example (even using an int argument) can be found on Microsoft's site:
How to: Run an Operation in the Background

Check out the DoWorkEventArgs.Argument Property:
...
backgroundWorker1.RunWorkerAsync(yourInt);
...
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Do not access the form's BackgroundWorker reference directly.
// Instead, use the reference provided by the sender parameter.
BackgroundWorker bw = sender as BackgroundWorker;
// Extract the argument.
int arg = (int)e.Argument;
// Start the time-consuming operation.
e.Result = TimeConsumingOperation(bw, arg);
// If the operation was canceled by the user,
// set the DoWorkEventArgs.Cancel property to true.
if (bw.CancellationPending)
{
e.Cancel = true;
}
}

you can try this out if you want to pass more than one type of arguments, first add them all to an array of type Object and pass that object to RunWorkerAsync() here is an example :
some_Method(){
List<string> excludeList = new List<string>(); // list of strings
string newPath ="some path"; // normal string
Object[] args = {newPath,excludeList };
backgroundAnalyzer.RunWorkerAsync(args);
}
Now in the doWork method of background worker
backgroundAnalyzer_DoWork(object sender, DoWorkEventArgs e)
{
backgroundAnalyzer.ReportProgress(50);
Object[] arg = e.Argument as Object[];
string path= (string)arg[0];
List<string> lst = (List<string>) arg[1];
.......
// do something......
//.....
}

You need RunWorkerAsync(object) method and DoWorkEventArgs.Argument property.
worker.RunWorkerAsync(5);
private void worker_DoWork(object sender, DoWorkEventArgs e) {
int argument = (int)e.Argument; //5
}

You should always try to use a composite object with concrete types (using composite design pattern) rather than a list of object types. Who would remember what the heck each of those objects is? Think about maintenance of your code later on... Instead, try something like this:
Public (Class or Structure) MyPerson
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public int ZipCode { get; set; }
End Class
And then:
Dim person as new MyPerson With { .FirstName = “Joe”,
.LastName = "Smith”,
...
}
backgroundWorker1.RunWorkerAsync(person)
and then:
private void backgroundWorker1_DoWork (object sender, DoWorkEventArgs e)
{
MyPerson person = e.Argument as MyPerson
string firstname = person.FirstName;
string lastname = person.LastName;
int zipcode = person.ZipCode;
}

Related

Dynamic arguments for events [duplicate]

Let's say I want to pass some extra data when assigning an event handler. Consider the following code:
private void setup(string someData)
{
Object.assignHandler(evHandler);
}
public void evHandler(Object sender)
{
// need someData here!!!
}
How would I go about getting someData into my evHandler method?
private void setup(string someData)
{
Object.assignHandler((sender) => evHandler(sender,someData));
}
public void evHandler(Object sender, string someData)
{
// need someData here!!!
}
I had a hard time figuring out #spender's example above especially with: Object.assignHandler((sender) => evHandler(sender,someData)); because there's no such thing as Object.assignHandler in the literal sense. So I did a little more Googling and found this example. The answer by Peter Duniho was the one that clicked in my head (this is not my work):
snip
The usual approach is to use an anonymous method with an event handler
that has your modified signature. For example:
void Onbutton_click(object sender, EventArgs e, int i) { ... }
button.Click += delegate(object sender, EventArgs e)
{ Onbutton_click(sender, e, 172); };
Of course, you don't have to pass in 172, or even make the third parameter
an int. :)
/snip
Using that example I was able to pass in two custom ComboBoxItem objects to a Timer.Elapsed event using lambda notation:
simulatorTimer.Elapsed +=
(sender, e) => onTimedEvent(sender, e,
(ComboBoxItem) cbPressureSetting.SelectedItem,
(ComboBoxItem) cbTemperatureSetting.SelectedItem);
and then into it's handler:
static void onTimedEvent(object sender, EventArgs e, ComboBoxItem pressure, ComboBoxItem temperature)
{
Console.WriteLine("Requested pressure: {0} PSIA\nRequested temperature: {1}° C", pressure, temperature);
}
This isn't any new code from the examples above, but it does demonstrate how to interpret them. Hopefully someone like me finds it instructive & useful so they don't spend hours trying to understand the concept like I did.
This code works in my project (except for a non-thread-safe exception with the ComboBoxItem objects that I don't believe changes how the example works). I'm figuring that out now.
Captured variables:
private void setup(string someData)
{
Object.assignHandler((sender,args) => {
evHandler(sender, someData);
});
}
public void evHandler(Object sender, string someData)
{
// use someData here
}
Or (C# 2.0 alternative):
Object.assignHandler((EventHandler)delegate(object sender,EventArgs args) {
evHandler(sender, someData);
});
you can try doing this:
string yourObject;
theClassWithTheEvent.myEvent += (sender, model) =>
{
yourObject = "somthing";
}
My question that was similar was marked a duplicate so thought I'd add an answer here since it won't let me on my question.
class Program
{
delegate void ComponentEventHandler(params dynamic[] args);
event ComponentEventHandler onTest;
static void Main(string[] args)
{
Program prg = new Program();
// can be bound to event and called that way
prg.onTest += prg.Test;
prg.onTest.Invoke("What", 5, 12.0);
Console.ReadKey();
}
public void Test(params dynamic[] values)
{
// assign our params to variables
string name = values[0];
int age = values[1];
double value = values[2];
Console.WriteLine(name);
Console.WriteLine(age);
Console.WriteLine(value);
}
}
Well, the simplest method id to make someData a member variable like so:
public class MyClass
{
private string _eventData;
private void setup(string someData)
{
_eventData = someData;
Object.assignHandler(evHandler);
}
public void evHandler()
{
// do something with _eventData here
}
}
I'm not sure that's the best way to do it, but it really depends on the event type, the object, etc.
You could create a custom object having additional properties based on Object:
class CustomObject : Object
{
public string SomeData;
}
private void setup(string someData)
{
CustomObject customObject = new CustomObject { SomeData = someData };
CustomObject.assignHandler(evHandler);
}
public void evHandler(Object sender)
{
string someData = ((CustomObject)sender).SomeData;
}
If the data should not be changed anymore after initialization, you could also add a custom constructor, for example.
Here is my one-line solution that pass extra parameters to a timer handler.
private void OnFailed(uint errorCode, string message)
{
ThreadPoolTimer.CreateTimer((timer) => {
UI.ErrorMessage = string.Format("Error: 0x{0:X} {1}", errorCode, message);
}, System.TimeSpan.FromMilliseconds(100));
}
This solution offers a way to pass extra parameters to an event handler while still allowing to unsubscibe:
Within the Subscribe() function of my example I create an Action that invokes a lambda function that supplies my event handler with the event args and my extra parameter. I then store this Action in a dictionary. When I want to unsubscribe, I can use the stored Actions to do so.
This works, I read the length of listeners before and after unsubscribing and it did decrease - you can unsubscribe again without problems.
public class Player
{
public Action<JumpInfo> OnJump;
}
public class PlayerJumpListener
{
public List<Player> MyPlayerList;
private Dictionary<Player, Action<JumpInfo>> _jumpActionsByPlayer = new Dictionary<Player, Action<JumpInfo>>();
private void Subscribe()
{
foreach (Player player in MyPlayerList)
{
Action<JumpInfo> playerJumpAction = (jumpInfo) => HandlePlayerJump(jumpInfo, player);
player.OnJump += playerJumpAction;
_jumpActionsByPlayer.Add(player, playerJumpAction);
}
}
private void Unsubscibe()
{
foreach (KeyValuePair<Player, Action<JumpInfo>> kvp in _jumpActionsByPlayer)
{
kvp.Key.OnJump -= kvp.Value;
}
}
private void HandlePlayerJump(JumpInfo jumpInfo, Player player)
{
// player jumped
}
}
I scoured the internet before a coworker kindly helped me, and boy I felt dumb. Brackets is the solution for the EventHandler.
Ex.
event EventHandler<(int, bool)> EventName;
and then pick it up with:
private void Delegate_EventName(object sender, (int, bool) e)
you can then access the info:
var temp = e.Item1;<br>
var temp2 = e.Item2;<br>
or you can add names as you would expect for parameters and call them via e:
private void Delegate_EventName(object sender, (int num, bool val) e)
you can then access the info:
var temp = e.num;
var temp2 = e.val;

User interaction in non-UI thread?

in my WPF - C# application, I have a time consuming function, which I execute with a BackgroundWorker. The job of this function is to add given data from a file into a database. Now and then, I need some user feedback, for example the data is already in the store and I want to ask the user, whether he wants to merge the data or create a new object or skip the data completely. Much like the dialog windows shows, if I try to copy a file to a location, where a file with the same name already exists.
The problem is, that I cannot call a GUI-window from a non GUI-thread. How could I implement this behavior?
Thanks in advance,
Frank
You could work with EventWaitHandle ou AutoResetEvent, then whenever you want to prompt the user, you could the signal UI, and then wait for the responde. The information about the file could be stored on a variable.
If possible... my suggestion is to architect your long running task into atomic operations. Then you can create a queue of items accessible by both your background thread and UI thread.
public class WorkItem<T>
{
public T Data { get; set; }
public Func<bool> Validate { get; set; }
public Func<T, bool> Action { get; set; }
}
You can use something like this class. It uses a queue to manage the execution of your work items, and an observable collection to signal the UI:
public class TaskRunner<T>
{
private readonly Queue<WorkItem<T>> _queue;
public ObservableCollection<WorkItem<T>> NeedsAttention { get; private set; }
public bool WorkRemaining
{
get { return NeedsAttention.Count > 0 && _queue.Count > 0; }
}
public TaskRunner(IEnumerable<WorkItem<T>> items)
{
_queue = new Queue<WorkItem<T>>(items);
NeedsAttention = new ObservableCollection<WorkItem<T>>();
}
public event EventHandler WorkCompleted;
public void LongRunningTask()
{
while (WorkRemaining)
{
if (_queue.Any())
{
var workItem = _queue.Dequeue();
if (workItem.Validate())
{
workItem.Action(workItem.Data);
}
else
{
NeedsAttention.Add(workItem);
}
}
else
{
Thread.Sleep(500); // check if the queue has items every 500ms
}
}
var completedEvent = WorkCompleted;
if (completedEvent != null)
{
completedEvent(this, EventArgs.Empty);
}
}
public void Queue(WorkItem<T> item)
{
// TODO remove the item from the NeedsAttention collection
_queue.Enqueue(item);
}
}
Your UI codebehind could look something like
public class TaskRunnerPage : Page
{
private TaskRunner<XElement> _taskrunner;
public void DoWork()
{
var work = Enumerable.Empty<WorkItem<XElement>>(); // TODO create your workItems
_taskrunner = new TaskRunner<XElement>(work);
_taskrunner.NeedsAttention.CollectionChanged += OnItemNeedsAttention;
Task.Run(() => _taskrunner.LongRunningTask()); // run this on a non-UI thread
}
private void OnItemNeedsAttention(object sender, NotifyCollectionChangedEventArgs e)
{
// e.NewItems contains items that need attention.
foreach (var item in e.NewItems)
{
var workItem = (WorkItem<XElement>) item;
// do something with workItem
PromptUser();
}
}
/// <summary>
/// TODO Use this callback from your UI
/// </summary>
private void OnUserAction()
{
// TODO create a new workItem with your changed parameters
var workItem = new WorkItem<XElement>();
_taskrunner.Queue(workItem);
}
}
This code is untested! But the basic principle should work for you.
Specifically to your case
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
Thread.Sleep(1000);
var a = Test1("a");
Thread.Sleep(1000);
var b = (string)Invoke(new Func<string>(() => Test2("b")));
MessageBox.Show(a + b);
}
private string Test1(string text)
{
if (this.InvokeRequired)
return (string)this.Invoke(new Func<string>(() => Test1(text)));
else
{
MessageBox.Show(text);
return "test1";
}
}
private string Test2(string text)
{
MessageBox.Show(text);
return "test2";
}
Test2 is a normal method which you have to invoke from background worker. Test1 can be called directly and uses safe pattern to invoke itself.
MessageBox.Show is similar to yourForm.ShowDialog (both are modal), you pass parameters to it (text) and you return value (can be a value of property of yourForm which is set when form is closed). I am using string, but it can be any data type obviously.
From the input of the answers here, I came to the following solution:
(Mis)Using the ReportProgress-method of the Backgroundworker in Combination with a EventWaitHandle. If I want to interact with the user, I call the ReportProgress-method and setting the background process on wait. In the Handler for the ReportProgress event I do the interaction and when finished, I release the EventWaitHandle.
BackgroundWorker bgw;
public MainWindow()
{
InitializeComponent();
bgw = new BackgroundWorker();
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
bgw.WorkerReportsProgress = true;
bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
}
// Starting the time consuming operation
private void Button_Click(object sender, RoutedEventArgs e)
{
bgw.RunWorkerAsync();
}
// using the ProgressChanged-Handler to execute the user interaction
void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
UserStateData usd = e.UserState as UserStateData;
// UserStateData.Message is used to see **who** called the method
if (usd.Message == "X")
{
// do the user interaction here
UserInteraction wnd = new UserInteraction();
wnd.ShowDialog();
// A global variable to carry the information and the EventWaitHandle
Controller.instance.TWS.Message = wnd.TextBox_Message.Text;
Controller.instance.TWS.Background.Set();
}
}
void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show(e.Result.ToString());
}
// our time consuming operation
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
Thread.Sleep(2000);
// need 4 userinteraction: raise the ReportProgress event and Wait
bgw.ReportProgress(0, new UserStateData() { Message = "X", Data = "Test" });
Controller.instance.TWS.Background.WaitOne();
// The WaitHandle was released, the needed information should be written to global variable
string first = Controller.instance.TWS.Message.ToString();
// ... and again
Thread.Sleep(2000);
bgw.ReportProgress(0, new UserStateData() { Message = "X", Data = "Test" });
Controller.instance.TWS.Background.WaitOne();
e.Result = first + Controller.instance.TWS.Message;
}
I hope I did not overlooked some critical issues. I'm not so familar with multithreading - maybe there should be some lock(object) somewhere?

NullReferenceException when attempting to fire an event

I'm learning about creating events and creating multi-threaded applications.
The method Thread is called by another class which populates the params with search conditions. A BackgroundWorker is created, performs a search and returns the results to worker_RunWorkerCompleted.
Within worker_RunWorkerCompleted, I want to send the results back to my UI which is subscribing to the Fireendofsearch event.
I'm having trouble understanding why my code below throws the following error
Object reference not set to an instance of an object.
when I fire the event Fireendofsearch
public class BackgroundSearch
{
public event SearchResultCompleteThreaded Fireendofsearch;
public EventArgs a = null;
public delegate void SearchResultCompleteThreaded(object seachresults, EventArgs a);
internal void Thread(string folder, string parms)
{
var Argument = new List<object> { folder, parms };
var worker = new BackgroundWorker {WorkerReportsProgress = false, WorkerSupportsCancellation = false};
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.RunWorkerAsync(Argument);
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
var passedAugue = e.Argument as List<object>;
var returnResult = new List<string[]>();
if (passedAugue != null)
{
var result = Directory.GetFiles(passedAugue[0].ToString(), passedAugue[1].ToString(), SearchOption.AllDirectories);
foreach (string s in result)
{
var t = new string[4];
t[0] = s;
t[1] = File.GetCreationTime(s).ToString();
t[2] = File.GetLastAccessTime(s).ToString();
t[3] = File.GetLastWriteTime(s).ToString();
returnResult.Add(t);
}
}
if (returnResult.Count != 0)
{
e.Result = returnResult;
}
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Result != null)
{
Fireendofsearch(e.Result, a);
}
}
}
Firendofsearch will be null until someone subscribes to it, change your work completed event handler to this to fix it.
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Result != null)
{
var friendOfSearch = Fireendofsearch;
if(friendOfSearch != null)
friendOfSearch (e.Result, a);
}
}
The reason I copy it to a variable is if someone in another thread is the last person to unsubscribe between the null check and the raising of the event you will still get the null reference exception, by coping to another variable first it solves that problem.
However I would make some other changes if I where writing it, you are retuning a null EventArgs for some reason and passing the result back as the "Sender" in the traditional event pattern. I would change your code to this
public event EventHandler<FriendOfSearchArgs> FirendsOfSearch;
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Result != null)
{
RaiseFriendOfSearch(e.Result);
}
}
protected virtual void RaiseFriendOfSearch(object result)
{
var friendOfSearch = FirendsOfSearch;
if(friendOfSearch != null)
friendOfSearch(this, new FriendOfSearchArgs(result));
}
public class FriendOfSearchArgs : EventArgs
{
public FriendOfSearchArgs(object result)
{
Result = result;
}
public object Result {get; private set;}
}
This was all written in the SO text box so there may be one or two errors.
You should check for null before trying to invoke the delegate. And you have to pull it into a separate variable first to avoid threading issues.
var ev = Fireendofsearch;
if ( ev != null ) ev( ... );
I have also found it useful to have an extension method for this case:
public static void Raise ( this EventHandler h, object sender )
{
if ( h != null) h( sender, EventArgs.Empty );
}
And then:
MyEvent.Raise ( this );
"Behind" your public event, there's an implicit private variable of type SearchResultCompleteThreaded. The type SearchResultCompleteThreaded is a delegate type.
In .NET all delegates are "multicast" delegates. That means they have an invocation list (your GetInvocationList() method on SearchResultCompleteThreaded is derived from System.Delegate.GetInvocationList().
Now, in .NET, the invocation list is guaranteed to consist of one or more items (not zero or more). Any delegate type is an immutable type. But if you try to create a new instance by "subtracting away" all members in the invocation list of an existing instance, as in var newDel = oldDel - oldDel; or reuseDel -= reuseDel;, then instead of getting a new instance with a zero-length invocation list, you get a null reference!
The good thing about this is that you don't have to worry about a subtle difference between an "empty" delegate instance (which could otherwise have been permitted) and a null reference. The bad thing about it, is the problem you had above.
For some reason (Optimization most likely), an event is only instantiated when a first handler method subscribe to it.
You must check for that in your code.
Here's how I usually declare an event:
public event SearchResultCompleteThreaded Fireendofsearch;
private void RaiseFireEndOfSearchEvent(EventArgs e)
{
if (Fireendofsearch != null)
{
Fireendofsearch(this, e);
}
}
And whenever I need to raise the event, I would just call the helper method instead.
Set:
public event SearchResultCompleteThreaded Fireendofsearch = delegate { };
Needs initialized possibly?

Pass extra parameters to an event handler?

Let's say I want to pass some extra data when assigning an event handler. Consider the following code:
private void setup(string someData)
{
Object.assignHandler(evHandler);
}
public void evHandler(Object sender)
{
// need someData here!!!
}
How would I go about getting someData into my evHandler method?
private void setup(string someData)
{
Object.assignHandler((sender) => evHandler(sender,someData));
}
public void evHandler(Object sender, string someData)
{
// need someData here!!!
}
I had a hard time figuring out #spender's example above especially with: Object.assignHandler((sender) => evHandler(sender,someData)); because there's no such thing as Object.assignHandler in the literal sense. So I did a little more Googling and found this example. The answer by Peter Duniho was the one that clicked in my head (this is not my work):
snip
The usual approach is to use an anonymous method with an event handler
that has your modified signature. For example:
void Onbutton_click(object sender, EventArgs e, int i) { ... }
button.Click += delegate(object sender, EventArgs e)
{ Onbutton_click(sender, e, 172); };
Of course, you don't have to pass in 172, or even make the third parameter
an int. :)
/snip
Using that example I was able to pass in two custom ComboBoxItem objects to a Timer.Elapsed event using lambda notation:
simulatorTimer.Elapsed +=
(sender, e) => onTimedEvent(sender, e,
(ComboBoxItem) cbPressureSetting.SelectedItem,
(ComboBoxItem) cbTemperatureSetting.SelectedItem);
and then into it's handler:
static void onTimedEvent(object sender, EventArgs e, ComboBoxItem pressure, ComboBoxItem temperature)
{
Console.WriteLine("Requested pressure: {0} PSIA\nRequested temperature: {1}° C", pressure, temperature);
}
This isn't any new code from the examples above, but it does demonstrate how to interpret them. Hopefully someone like me finds it instructive & useful so they don't spend hours trying to understand the concept like I did.
This code works in my project (except for a non-thread-safe exception with the ComboBoxItem objects that I don't believe changes how the example works). I'm figuring that out now.
Captured variables:
private void setup(string someData)
{
Object.assignHandler((sender,args) => {
evHandler(sender, someData);
});
}
public void evHandler(Object sender, string someData)
{
// use someData here
}
Or (C# 2.0 alternative):
Object.assignHandler((EventHandler)delegate(object sender,EventArgs args) {
evHandler(sender, someData);
});
you can try doing this:
string yourObject;
theClassWithTheEvent.myEvent += (sender, model) =>
{
yourObject = "somthing";
}
My question that was similar was marked a duplicate so thought I'd add an answer here since it won't let me on my question.
class Program
{
delegate void ComponentEventHandler(params dynamic[] args);
event ComponentEventHandler onTest;
static void Main(string[] args)
{
Program prg = new Program();
// can be bound to event and called that way
prg.onTest += prg.Test;
prg.onTest.Invoke("What", 5, 12.0);
Console.ReadKey();
}
public void Test(params dynamic[] values)
{
// assign our params to variables
string name = values[0];
int age = values[1];
double value = values[2];
Console.WriteLine(name);
Console.WriteLine(age);
Console.WriteLine(value);
}
}
Well, the simplest method id to make someData a member variable like so:
public class MyClass
{
private string _eventData;
private void setup(string someData)
{
_eventData = someData;
Object.assignHandler(evHandler);
}
public void evHandler()
{
// do something with _eventData here
}
}
I'm not sure that's the best way to do it, but it really depends on the event type, the object, etc.
You could create a custom object having additional properties based on Object:
class CustomObject : Object
{
public string SomeData;
}
private void setup(string someData)
{
CustomObject customObject = new CustomObject { SomeData = someData };
CustomObject.assignHandler(evHandler);
}
public void evHandler(Object sender)
{
string someData = ((CustomObject)sender).SomeData;
}
If the data should not be changed anymore after initialization, you could also add a custom constructor, for example.
Here is my one-line solution that pass extra parameters to a timer handler.
private void OnFailed(uint errorCode, string message)
{
ThreadPoolTimer.CreateTimer((timer) => {
UI.ErrorMessage = string.Format("Error: 0x{0:X} {1}", errorCode, message);
}, System.TimeSpan.FromMilliseconds(100));
}
This solution offers a way to pass extra parameters to an event handler while still allowing to unsubscibe:
Within the Subscribe() function of my example I create an Action that invokes a lambda function that supplies my event handler with the event args and my extra parameter. I then store this Action in a dictionary. When I want to unsubscribe, I can use the stored Actions to do so.
This works, I read the length of listeners before and after unsubscribing and it did decrease - you can unsubscribe again without problems.
public class Player
{
public Action<JumpInfo> OnJump;
}
public class PlayerJumpListener
{
public List<Player> MyPlayerList;
private Dictionary<Player, Action<JumpInfo>> _jumpActionsByPlayer = new Dictionary<Player, Action<JumpInfo>>();
private void Subscribe()
{
foreach (Player player in MyPlayerList)
{
Action<JumpInfo> playerJumpAction = (jumpInfo) => HandlePlayerJump(jumpInfo, player);
player.OnJump += playerJumpAction;
_jumpActionsByPlayer.Add(player, playerJumpAction);
}
}
private void Unsubscibe()
{
foreach (KeyValuePair<Player, Action<JumpInfo>> kvp in _jumpActionsByPlayer)
{
kvp.Key.OnJump -= kvp.Value;
}
}
private void HandlePlayerJump(JumpInfo jumpInfo, Player player)
{
// player jumped
}
}
I scoured the internet before a coworker kindly helped me, and boy I felt dumb. Brackets is the solution for the EventHandler.
Ex.
event EventHandler<(int, bool)> EventName;
and then pick it up with:
private void Delegate_EventName(object sender, (int, bool) e)
you can then access the info:
var temp = e.Item1;<br>
var temp2 = e.Item2;<br>
or you can add names as you would expect for parameters and call them via e:
private void Delegate_EventName(object sender, (int num, bool val) e)
you can then access the info:
var temp = e.num;
var temp2 = e.val;

Passing a method to a backgroundworker dowork

In the code below, is there a way to instead of always subscribing the updateWorker_DoWork method, pass it a method like this
public void GetUpdates(SomeObject blah)
{
//...
updateWorker.DoWork += new DoWorkEventHandler(blah);
//...
}
public void GetUpdates()
{
//Set up worker
updateWorker.WorkerReportsProgress = true;
updateWorker.WorkerSupportsCancellation = true;
updateWorker.DoWork += new DoWorkEventHandler(updateWorker_DoWork);
updateWorker.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(updateWorker_RunWorkerCompleted);
updateWorker.ProgressChanged +=
new ProgressChangedEventHandler(updateWorker_ProgressChanged);
//Run worker
_canCancelWorker = true;
updateWorker.RunWorkerAsync();
//Initial Progress zero percent event
_thes.UpdateProgress(0);
}
For your RunWorkerAsync() you can pass any argument you like. You can just put a Func() or Action() into it and in your DoWork() you just cast the object back to this specific type and call it.
Examples are here and here.
private void InitializeBackgroundWorker()
{
_Worker = new BackgroundWorker();
// On a call cast the e.Argument to a Func<TResult> and call it...
// Take the result from it and put it into e.Result
_Worker.DoWork += (sender, e) => e.Result = ((Func<string>)e.Argument)();
// Take the e.Result and print it out
// (cause we will always call a Func<string> the e.Result must always be a string)
_Worker.RunWorkerCompleted += (sender, e) =>
{
Debug.Print((string)e.Result);
};
}
private void StartTheWorker()
{
int someValue = 42;
//Take a method with a parameter and put it into another func with no parameter
//This is called currying or binding
StartTheWorker(new Func<string>(() => DoSomething(someValue)));
while(_Worker.IsBusy)
Thread.Sleep(1);
//If your function exactly matches, just put it into the argument.
StartTheWorker(AnotherTask);
}
private void StartTheWorker(Func<string> func)
{
_Worker.RunWorkerAsync(func);
}
private string DoSomething(int value)
{
return value.ToString("x");
}
private string AnotherTask()
{
return "Hello World";
}
If I didn't misunderstand you, you need lambda expressions to construct anonymous method.
updateWorker.DoWork += (sender,e)=>
{
//bla
}
Now you needn't always to write a method and pass it to new DoWorkEventHandler(myMethod)
Worked it out, was way simpler than I was thinking. Just had to make a delegate for the method called on DoWork. Probably should have phrased my original question better.
public delegate void DoWorkDelegate(object sender,DoWorkEventArgs e);
public void GetUpdates()
{
StartWorker(new DoWorkDelegate(updateWorker_DoWork));
}
public void StartWorker(DoWorkDelegate task)
{
//Set up worker
updateWorker.WorkerReportsProgress = true;
updateWorker.WorkerSupportsCancellation = true;
updateWorker.DoWork += new DoWorkEventHandler(task);
updateWorker.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(updateWorker_RunWorkerCompleted);
updateWorker.ProgressChanged +=
new ProgressChangedEventHandler(updateWorker_ProgressChanged);
//Run worker
_canCancelWorker = true;
updateWorker.RunWorkerAsync();
//Initial Progress zero percent event
_thes.UpdateProgress(0);
}
private void updateWorker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
e.Result = GetUpdatesTask(worker, e);
}

Categories

Resources