« first day (2749 days earlier)      last day (2204 days later) » 

10:00 AM
Welp, there's always the possibility of muting you
Shall we try that?
 
you can try
 
Now now, let's remain civil shall we?
 
What is civil?
Baby don't hurt me, don't hurt me, no more.
can we make this happen?
that cap responds to /what is [a-z]+\?/i with "Baby don't hurt me, don't hurt me, no more!"
same as with stop
 
HAMMERTIME!
 
Wouldn't you have to directly code that into her source? On the fly we can just update the !! listener AFAIK
!!info stop
 
10:07 AM
HAMMERTIME!
@Squirrelkiller Command stop, created by Wulworine on Fri, 23 May 2014 10:01:31 GMT
 
!!stop
 
Guys I need a help, please see the code below,

var emp = from e in Employee.GetAllEmployees()
join d in Department.GetAllDepartments()
on e.DepartmentID equals d.ID into eGroup
from xx in eGroup.DefaultIfEmpty()
select new
{
Employee = e.Name,
Departmentss = d.DepartmentID
};

it says d does not exist in the current context
 
lol its two commands
!!tell Alex format
 
@Alex Format your code - hit Ctrl+K before sending and see the faq
 
10:08 AM
  var emp = from e in Employee.GetAllEmployees()
                      join d in Department.GetAllDepartments()
                      on e.DepartmentID equals d.ID into eGroup
                      from xx in eGroup.DefaultIfEmpty()
                      select new
                      {
                          Employee = e.Name,
                          Departmentss = d.DepartmentID
                      };
 
And here I was happy without having to deal with JS bullshit. Now I have to guess why the auth header isn't being sent.
 
You're doing a groupjoin, aren't you? d exists only in the scope of the groupjoin.
It helps define eGroup.
 
I want to do left outer join
 
Basically what you have at the select stage is e (the employee) and eGroup (the list of departments for e);
 
is join like Zip in method chain?
 
10:10 AM
You just need to use xx instead of d.
xx is the department in the iteration over eGroup.
 
why I can't use d ? becuase you can see I am using e as well
 
Don't you need d.ID instead of d.DepartmentID?
 
@AlexanderZaldostanov e is inthe scope of the entire query. d is just defined in the join ... into clause. That's how it works.
 
> from e
from xx
no from d
 
Basically, you want to split eGroup into a sequence of {empId, deptId}?
 
10:12 AM
@HéctorÁlvarez I need departmentID
 
I think either e.DepartmentID or d.ID would work according to that query, but not d.DepartmentID
 
@HéctorÁlvarez I don't think e.DepartmentId exists, since it seems a user can be in multiple departments.
 
guys when I enter d DOT it says d doesn't exist
 
why do we bring sql into C#?
i thought SQL was horrible to work with
 
10:14 AM
@AlexanderZaldostanov so don't do that
 
@AlexanderZaldostanov Yes, we repeatedly mentioned that d doesn't exist.
 
public class Department
    {
        public int ID { get; set; }
        public string Name { get; set; }

        public static List<Department> GetAllDepartments()
        {
            return new List<Department>()
        {
            new Department { ID = 1, Name = "IT"},
            new Department { ID = 2, Name = "HR"},
            new Department { ID = 3, Name = "Payroll"},
        };
        }
    }

    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
this is the entire code
I was just learning LINQ
 
LinqSQL is terrible
 
@AlexanderZaldostanov The first step of learning is asking questions. The second is listening to the answers.
2
 
Or whatever it's called
 
10:17 AM
@Wietlol it's HQL, and it's pretty solid.
 
yes, you shouldn't be performing joins in program
 
everytime I need to write SQL, I feel like the world spins the other way around
 
that's horribly inefficient
 
My question is that when I can use e then why I can't use d here ?
 
for the same reason you cant use d in this code
public void Foo()
{
    int i = d.ID;
}
d doesnt exist
 
10:18 AM
Actually d does exist, but isn't set to an instance of an object.
 
then why e exist because both are declared in same score aren't they ?
 
you want the d?
 
He wants the d.
 
nope, they arent in the same scope
 
@Neil Why not? Your joins aren't necessarily over a DB. Sometimes you need the semantics of a structured query over other data sources.
 
10:19 AM
did You know, that mines go off by pressing, not releasing?
 
@AvnerShahar-Kashtan Because you'd need to grab everything from one table and everything from another table for comparison
 
@Neil Also, even doing LINQ over DB entities using EF, for instance, doesn't perform the join in your program. It constructs the query and executes it in the DB.
 
did you know, that mines are supposed to provide resources and not blow up in your face?
 
whilst we're on the subject of explosives, im here
 
databases can optimize, and has the statistical data to know how to optimize
 
10:20 AM
@Neil Yes, which is why LINQ uses that.
 
Hollywood lied to us!
 
It's not always perfect, but hand-crafted queries often aren't as well. It's perfectly fine for 90% of queries I've encountered in recent years.
 
@AvnerShahar-Kashtan Employee.GetAllEmployees() isn't performing a query to get all records from employee table?
 
@Neil In this case? No, it returns a list created in memory.
 
@AvnerShahar-Kashtan at work, I have a database model and it takes EF 7 seconds to load my entity from the database
 
10:21 AM
In the general case? It should return an IQueryable<Employee>, which isn't the entirety of the dataset.
 
note that the "entity" is constructed of 502 records from the database
 
@AvnerShahar-Kashtan In the general case, you're still having to load all employees
 
the well-known N+1 problem
 
@Neil No. That's not how it works.
 
@Wietlol An entity is a row.
Please don't confuse entity sets and entities.
 
10:22 AM
you don't have to load it all in memory, but you do have to load all records
 
yea, but i need all the information of the entity, which includes all rows of a OneToMany relation
i need to transform it to Json, which means I need all data
 
IQueryable<Employee> allEmps = db.GetAllEmployees(); // no data is fetched.
allEmps = allEmps.Where(emp => emp.DeptId = 6); // still no data is fetched.
allEmps = allEmps.OrderBy(emp => emp.HiringDate); // still nothing.
foreach (var emp in allEmps) {}  // NOW the query is processed, SQL code generated, the query processed *in the DB* and only the relevant records returned, ordered.
At no point does GetAllEmployees() fetch all rows.
 
@Wietlol But you aren't pulling an entity, you are pulling an entity set.
 
why so?
 
@AvnerShahar-Kashtan Adding upon this. allEmps.ToList() also materializes the query and brings the data into memory.
 
10:25 AM
@HéctorÁlvarez Yeah, it's the same as iterating over it.
 
@AvnerShahar-Kashtan If that's the case, how could it build a query suited for say, mysql or sqllite, etc.
 
@Wietlol Because table = entity set, row = entity.
 
@Neil That's what Entity Framework does. That's the purpose of the library. It has specific providers for different DBs.
 
but i only load 1 user for example
isnt 1 user 1 entity?
 
You pull a group of rows from a table, you pull an entity set. which is a subset of the bigger entity set.
 
10:26 AM
They don't always generate the most optimized queries, but they can be tweaked. And as I said, they're fine for the general case.
 
> note that the "entity" is constructed of 502 records from the database
 
@AvnerShahar-Kashtan I'd have to see the query being launched to believe that, but I'll admit it doesn't work as I expected
 
every "user" has multiple "items"
i still load 1 user
 
@Neil If it worked the way you thought, it would be unusable.
 
Unless you literally have over 501 columns to conform a whole entity...
 
10:27 AM
but user + items = N records
 
There are still a lot of gotchas, and a wrong move can accidentally fetch in too much data, but you have to learn to use it.
 
In below query can someone explain me when how many scopes are there ?

var emp = from e in Employee.GetAllEmployees()
                      join d in Department.GetAllDepartments()
                      on e.DepartmentID equals d.ID into eGroup
                      from d in eGroup.DefaultIfEmpty()
                      select new
                      {
                          Employee = e.Name,
                          Departmentss = e.DepartmentID
                      };
 
i'd change it to a method chain
it will make things much clearer
imho
 
@Neil It does, otherwise it would be unbearable to handle, e.g. 800k rows from memory, sorting, rearranging, filtering...
 
In @AlexanderZaldostanov's example, if it was connected via EF, the only field that would actually be returned from the Department table would be the department's ID.
 
@Wietlol can you show me ?
 
lemme wind up my abomination
var empl = Employee.GetAllEmployees()
	.GroupJoin(Department.GetAllDepartments(), e => e.DepartmentID, d => d.ID, (e, eGroup) => new {e, eGroup})
	.SelectMany(@t => @t.eGroup.DefaultIfEmpty(), (@t, xx) => new
	{
		Employee = @t.e.Name,
//		Departmentss = d.DepartmentID
	});
 
1. You iterate over `e` in `AllEmployees`.
1.1. For each `e`, you generate an `eGroup` of departments. (I would call it empDepts or something).
1.2. For each d in `empDepts`, you create a new entity comprising e.Name (you're still in scope #1) and d.Id (department ID).
 
@Wietlol Thanks man
@AvnerShahar-Kashtan Thank you Avner :)
 
> new {e, eGroup}
afaik, you should use a Zip, not a GroupJoin
 
10:37 AM
@AlexanderZaldostanov As @Wietlol shows, when you change it to a the method chain syntax, the scope is clearer - GroupJoin (the equivalent to join...into) takes the original list and outputs a new list, that has both e and e's departments.
At this point, this collection of {e,eGroup} is your scope.
 
Employee::DepartmentID implies that every employee only ever has one department
 
@Wietlol What? No. Zip connects two collections of equal size into a shared object.
 
GroupJoin implies that every employee has 0, 1 or more departments
 
Ah, I see now.
 
ow, wait, that is true
 
10:38 AM
You're right, the groupjoin implies that there are multiple Departments with the same ID.
 
im not sure if there is an IEnumerable method that handles this
 
Ah, or 0. That works too.
 
but this is not really that hard
 
@AvnerShahar-Kashtan Thanks bud, I will
 
var departments = Department.GetAllDepartments()
	.ToDictionary(department => department.ID);

var empl = Employee.GetAllEmployees()
	.Select(employee => new
		{
			Employee = employee,
			Departments = departments[employee.DepartmentID], // fails if department isnt found but I dont give a shit about stupid TryGetValue
		});
that should work
if you are dealing with a database, using GetAllDepartments would be silly in the first place
but having a FindDepartmentById should definitely be available
 
10:49 AM
thanks Wietlol, I am just learning the LINQ at the moment, can you refer me to any docs where I can learn the basics
 
11:00 AM
may be the LINQ with you, young padawan
 
Hi
 
I am getting timeout exepction while trying to dump millions of records
using sql bulk copy
 
@User Don't do it in one batch, then.
 
11:03 AM
i prepare 1 datatable during my long running process of 1000 records and send it to bulk copy
i perform this whole in transaction so after some records are inserted if error comes then those records should also rollback
but in case of trransaction i get this error :
The transaction log for my database is full.
 
@SebastianL Thanks
 
After setting BulkCopyTimeout to 0 and having batchsize =1000 i get this error :
Could not allocate space for object 'dbo.Sales'.'PK_dbo.Sales' in database 'XYZ' because the 'PRIMARY' filegroup is full. Create disk space by deleting unneeded files, dropping objects in the filegroup, adding additional files to the filegroup, or setting autogrowth on for existing files in the filegroup.
 
Do you actually have any disk space?
 
I checked c drive was having 550 kb
 
Sounds like you've solved the mystery
 
11:14 AM
@AlexanderZaldostanov I learned this way of programming in Java
C#'s api is slightly different
it has some methods Java hasnt, it lacks some that Java has, but the general idea is the same
this is where I learned quite a bit from
(the main difference is that in C#, you dont have the ForEach method
except the ForAll in the parralel one, but that kinda defeats its purpose
Venkat Subramaniam also talked a bit about them
(again Jaba)
 
@RudiVisser but do you recommened having transaction during importing 12 millions of data in database?
 
Not when you have no disk space to hold said 12 million records, no
Otherwise, if you can survive the memory pressure I don't see why not
Splitting in to smaller batches wouldn't hurt though (can also give you the ability to pause / resume as needed for ex on error)
 
I prepare datatable with 1000 records send it to bulk copy for bulk insert
reason for transaction if error occurs then i would rollback previous batches also
but then 1 user told me it is bad to have a transaction for long going (17 millions bulk insert)
 
We regularly do inserts with 500k+ rows through multiple SqlBulkCopy usages without issue (in a single transaction)
I'm not sure what the recommended maximum size of a transaction is
But I can imagine the stress on the server whilst populating it & on commit
 
Ss what i thought is i will open connection each time and dont maintain a transaction but if error occurs then i will delete old records like below :
 
11:22 AM
As I said before you need to be able to deal with the pressure - all of that data that you're pushing will go to the transaction log prior to committal
 
using (SqlConnection connection =
                  new SqlConnection(connectionString))
            {
                connection.Open();
                using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString))
                {
                    bulkCopy.DestinationTableName = "dbo.Discrepancy";
                    bulkCopy.EnableStreaming = true;
                    try
                    {
                        bulkCopy.WriteToServer(dataTable);
                    }
                    catch(Exception ex)
But again this delete operation make log full because of 3 millions of data to delete and its damn slow
I cant do truncate which is very faster because i have condition in my sql query
 
Are you asking these questions because you've encountered a specific issue (other than running out of disk space) when using a transaction for all of them?
 
Yes
I have ask question
0
Q: Timeout exception even after setting timeout property for operation

UserTimeout issue: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.\r\nThe the statement has been terminated. I am having 17 millions of records to dump in my application database.These 12 million records are the result of compar...

 
Right - but that's because you're out of disk space
Not a timeout
 
Another way is may be i can create 1 dummy table in which i can keep on doing bulk insert and then if there is no error then at the end i can do
insert into select * from ...
and then truncate the table
Does this looks good>
?
 
11:30 AM
Doing a bulk insert to your real table or a temporary table likely won't make any difference, considering you're running out of disk space on your operation
Inserting it anywhere is likely to cause you to still run out of disk space
 
but if i dont use transaction and then try to delete records in case of error then delete is so damn slow
 
Have you considered inserting a larger hard drive
 
larger drive will solve my timeout issue and logs full issue in case of transaction also?
 
Taking into consideration that you don't have enough disk space to hold a transaction with 17 mil rows in it, I doubt you have enough disk space to hold a table with 17 mil rows in it either. So yes, a larger hard drive will solve your problem
 
11:35 AM
but 1 day disk will be full right
 
A quick question: Is it possible to set Wcf Service base address to Https?
 
@User Yes, and what do you expect to happen?
 
I am not getting what will be the best way to handle this
 
If you have 1GB of data and a disk that holds 500MB (a scaled down version of your scenario) - how do you expect to store that 1GB of data?
I am not getting what you're not getting. You don't have enough disk space on your database server to do what you want
 
Just use Pi storage
 
11:37 AM
right now i am taking this database to my colleague computer who uis having 10gb space in c drive
 
You don't need to save anything. Just find the digits of Pi which represent the data you want to have stored, then save the index of the digit
 
@User ok and when your code is running do you see his available disk space go down?
 
I havent checked it.I would be checking now.With bulk copy i have seen some answer saying that during bulk copy i need to set database recovery model to :Bulk logged
Is it true?
@Neil Are you suggesting me?
 
You can certainly reduce the size of your log files by switching to Bulk Logged or Simple recovery yes
 
@User Sure (I am also kidding, don't use pi..)
 
11:40 AM
But if you're working on pressured disk space on a database server, you have way bigger problems
 
but then switiching to this option will lead to database back up problem or recovery problem right?
 
It's a different recovery model sure - but I doubt you're using FULL recovery strategy to its full extent anyway
Not many people are, nor do they need it
But it's really a DBA thing, and it sounds like you don't have one
 
Right now i am using Full Revoery
I mean this was the default option
I havent set it
 
Indeed
What is your backup strategy?
 
right now i am working on my local so i dont take backup
Shall i set my revoery to simple?
What impact will it gonna create if i do so?
 
11:50 AM
Well none if you're not taking backups
 
When asking about Backup Strategy , He was asking about how many back up do you have ? Are they complete or incremental or both? How often do you do them ? On how many media type ? Do you have a rolling system ?
witch of those backup are store off line ?
 
@User Simple recovery means, everytime you take a backup, you save the database in that moment
If something were to happen in 2 hours, you'd lose all that data
Full recovery relies on keeping a log of everything happening since the last backup
It literally grows at the same rate as your database.. if you add a GB, your log grows a GB
So if you do that, you should be wary of that fact (in other words, consider turning off full recovery before performing bulk insertions)
Full recovery is a disk space tradeoff where it requires more disk space and more CPU to maintain, but you lose very very little
simple recovery is more traditional and saves more disk space, but you save only the last backup..
Depending on how you use your database, if you're ok with losing the last day's work, a simple backup every night could be sufficient
 
12:07 PM
Anyone has any idea how to inject dependencies with MEF (Managed Extensibility Framework)
Google turns up articles suggesting to use MEF as IoC container.
Otherwise what would you guys use to create an application providing binding plugins at runtime!
 
In my last project I simply wrote a my own AssemblyScanner class that allowed scanning and loading types from DLLs in the current folder.
IEnumerable<IPlugin> plugins = _assemblyScanner.InstantiateAll<IPlugin>()
 
@AvnerShahar-Kashtan Oh god the code injections.
 
I'm following a similar approach but it's failing with dependencies randomly. For some plugins it works, but some others it fails :|
 
@TusharTyagi Sounds pre-GAC.
 
@AvnerShahar-Kashtan How did you manage the dependencies of your dll? Let's say your assembly Foo requires Bar in its constructor. How do you bind that at runtime?
 
12:14 PM
Definitely pre-GAC.
 
Any wcf configuration "expert"? Is it possible to set a base address to https using wsbinding? I can't find any exemple of that even in the Orelly Wcf book Edition 4.
 
@HéctorÁlvarez Yup. It was a risk that management were willing to take, seeing as the service ran on a dedicated machine.
@TusharTyagi I don't remember. I think it just found it?
 
@HéctorÁlvarez pre-GAC?
And the most stupid thing is this is working just Fine with framework 4.x but not with Core!! And I have to write this in core
Assembly.Load is supposed to check in application bin but with core either I'm missing something or it's not checking there
 
12:40 PM
Hello. I'm working on an MVC app and I'm writing an Edit page for my Widget model. Some properties are editable by anyone, but the NumSpokes attribute should only be editable by the widget's owner. So I have:
@if (ViewBag.isOwner)
{
    @Html.EditorFor(model => model.NumSpokes, new { htmlAttributes = new { @class = "form-control" } })
}
else
{
    @Html.DisplayFor(model => model.NumSpokes, new { htmlAttributes = new { @class = "form-control" } })
}
This works OK, but I'm wondering if there's a more concise way to do this. I have about six other attributes that are also only editable by the owner, so it would be nice if I could condense this.
 
@Kevin Can you not make a single method that will perform this check on your behalf?
 
I don't suppose there's some kind of... Html.EditorOrDisplayFor(expression, bool isEditor, Object addtionalViewData) extension somewhere? I didn't see one in the docs.
@Neil I was thinking about writing EditorOrDisplayFor by myself, but if I wanted to do it right, it would have all the same signature variations that EditorFor does. With or without the additionalViewData, with or without the string specifying the editor template, etc.
 
@Kevin If you can do it neatly for all attributes, do it
would make the actual call a lot cleaner
 
Usually when I think "how come there isn't an existing solution for this thing that I assume is a very common use case?" that means that I'm doing something wrong.
For starters, I'm pretty sure if I do things this way, I can't use the [Required] attribute on any of my sometimes-editable properties, because the framework doesn't bind properties from a non-editable label
 
@Kevin Heh, nah, you should have more confidence in your own capabilities
So long as you're not writing an inefficient algorithm or writing ugly code, you shouldn't doubt yourself for the most part
 
12:50 PM
Absolutely do not do that
Doubt yourself constantly
 
You can't program thinking everything you do is wrong
 
If I'm not doing anything wrong, that means that among all of the people using the .net ecosystem, exactly zero of them ever thought to create a reusable component that they could share with others for the thing everyone wants to be dong. That's not a fun pill to swallow; it means the whole world is selfish and irrational
 
We're all fucking morons and if you think differently you're just lying to yourself.
 
There are no fuzzy feel good solutions here
 
everyone wants to be dong
Everyone
 
12:51 PM
@MikeTheLiar My point. Taking advice from others isn't an improvement
 
Wants to be
Dong
 
@Kevin If you think there might be a better way, nothing wrong with checking
But once you know, just go with it next time
You can't constantly doubt yourself
 
!!giphy ive been thinking with my gut since i was 14 years old
 
Ugh
 
12:55 PM
@Kevin I totally get you :-)
 
Maybe what people usually do is, always use EditorFor for a field even if the user doesn't have permission to edit, and disable it using the htmlAttributes property in the additionalViewData.
But then my six fields will look like greyed out text boxes to non-owners. I'd prefer them to just look like text. I wonder if I can change that with css.
 
CSS can even spy
 
Using an EditorFor for all fields (editable or not) would solve some other design problems I encountered earlier... Maybe that's what I'll do. Shouldn't be a security problem as long as I keep doing permissions checking on the server side.
Not actually sure how I'd write the expression to only include the disabled property when isOwner is true. I can't just do @Html.EditorFor(model => model.NumSpokes, new { htmlAttributes = new { @class = "form-control", disabled = (ViewBag.isOwner ? "" : "disabled"} }) because an html input is disabled as long as it has a disabled property with any value, including the empty string.
Uh, I think.
 
You can write more than one method
A method to enable/disable would be useful
 
1:10 PM
Is it possible to create an anonymous type that sometimes has a property and sometimes doesn't, based on a ternary or similar?
 
@Kevin You'd want dynamic for that.
Or simply a null value for the property.
 
You can just pass null and then treat that case in your method
 
I would prefer not to have a method at all if I can help it.
 
But if you're creating a set of instances of the same anonymous type (say, list.Select(item => new { Prop1 = item.Name, Prop2 = item.Status}), then these instances always have the same fields
After all, they are a class that's generated behind the scenes.
 
Hmm, good point. If anonymous types generate their class at compile time, then I can't change what properties they have at run time.
Once again I'm asking myself "why isn't this common use case easy?" which makes me think I'm going down another blind alley
 
1:14 PM
well, would there be a way to save the method into a variable and invoke it?
 
The concept of checking whether a property exists or not is common in javascript, where the type system is dynamic by nature.
 
if so, you could perform the IsOwner check exactly once, save the method, then call it for all your attributes
 
For C#, it's not the accepted approach.
 
stackoverflow.com/questions/29153266/… suggests @Html.EditorFor(model => model.Quantity, ViewBag.Readonly ? (object)new { htmlAttributes = new { @readonly = "readonly", @class = "form-control" }} : new { htmlAttributes = new { @class = "form-control" } }) which is... Not beautiful.
 
Code rarely is.
But personally I don't see any glaring problems with that other than the repetition. I feel like it could be made more succinct.
 
1:26 PM
New roadblock: input elements with the disabled property don't get sent via post data. elements with the readonly property do (I think), but only some types of input are allowed to have that property. <select> elements, in particular, do not support it.
So if I want to make a field read-only, I have to accept that sometimes the value won't get bound on the server side. Which is the situation I was already in when I wrote EditorOrDisplayFor. So it's no better.
 
1:41 PM
@Kevin You could just do what I do in these situations. Write it all out meaning to come back later and find a solution for it when there are less pressing concerns and then forget all about it
 
This is my most pressing concern because it's the last thing I need to do before we push to QA
I could make EditorOrDisplayFor always post data, but only if I could return either (an EditorFor) or (a DisplayFor plus a HiddenFor), but I don't see an obvious way to concatenate MvcHtmlString instances.
I guess I could do:
            var x = htmlHelper.DisplayFor(expression, additionalViewData);
            var y = htmlHelper.HiddenFor(expression);
            return MvcHtmlString.Create(x.ToString() + y.ToString());
But this assumes that ToString() always returns a value that is a valid html segment, that those segments can be concatenated and still be valid, and that .Create() doesn't do any kind of encoding on its argument in order to "helpfully" prevent code injection or whatever
 
Hi everyone, anyone here proficient with C# background workers?
 
I'm proficient with not using them since 2010 or so.
 
Great, do you mind if I ask you a question?
 
Is it "Should I use BackgroundWorker"? If so, I know the answer to that. :)
But ask, ask. Always ask. Don't ask if you can ask. Just ask.
Ask the room, not a person. Ask, and if someone knows and/or cares, they will answer.
 
1:49 PM
Ok, understood. Thanks
 
Is DoubleTrouble when you have floating point math approximation issues?
 
haha it's a pun, yes
Ok, I'm trying to use a BackgroundWorker to start start a subscription to a message queue. My DoWork basically just starts the subscription that then will run indefinitely.

That works great. However when it comes to canceling the worker I would like to call CancelAsync but I'm not sure how to do it in the best way.

When I receive and process a new message from the queue I of course check if CancellationPending == true. But sometimes the messages comes very infrequently and I would like to cancel without waiting for a new message
Should I create a time that checks for the state of CancellationPending variable every second or so?
timer*
Or can I observe the state of the background worker somehow?
 
Generally speaking, it's the background worker's job to quit when requested.
So yeah, if you're blocking and waiting for a message, you'll have to make sure you're also waiting for a cancellation signal.
I don't know what kind of queue you're blocking on, but it might be possible to await on two things together.
But the simplest way, crude as it is, might be to add a timeout to your blocking queue listener, say 1 second, check for cancellation and re-block.
 

« first day (2749 days earlier)      last day (2204 days later) »