Callcontext and Multithreading

Source: Internet
Author: User

Some time ago, we had to go to a webpageProgramAn attempt to initiate a multi-threaded call to multiple components was made by other teams (such as India and Russia ).CodeIt seems unrealistic, but what's annoying is that appcontext is widely used in their code. the current object (in fact, httpcontext is used. current. ), and once asynchronous, httpcontext. the current will no longer exist, and naturally it will not stop reporting null reference exceptions, it seems that asynchronous is not realistic.

When there was nothing to do, I suddenly found a strange class called callcontext, hiding in system. runtime. remoting. messaging is almost useless under the namespace. Of course, at the beginning, I was only attracted by its name. Isn't it simply the call context? It seems that this thing can be helpful. So I checked msdn and described it as follows:

Provides the property set transmitted along with the Execution Code path. This class cannot be inherited.

A nonsense... Let's take a look at the remarks:

CallcontextIt is a special collection object similar to a method call thread in the local storage area, and provides a data slot that is unique to each logic execution thread. The data slot is not shared between call contexts on other logic threads. WhenCallcontextYou can add an object to it when it is propagated back and forth along the Execution Code path and checked by each object in the path.

When you call a remote method for an object in another appdomain,CallcontextClass will generate a logicalcallcontext instance that is propagated together with the remote call. Only the ilogicalthreadaffinative interface is exposed and stored inCallcontextObjects inLogicalcallcontextSpreadAppdomainExternal. The object that does not support this interface is notLogicalcallcontextTransmitted together with remote method calls in the instance.

It seems to have some meaning, but the definition of the logical thread seems to be somewhat ambiguous. However, I also mentioned an interface ilogicalthreadaffinative. Let's look at what this interface defines and look at the member definition... No member... An empty interface, sweating a bit, let's see how it is described on msdn:

The object that can be propagated to the external appdomain in logicalcallcontext.

The role of remoting is emphasized. Let's take a look at the remarks:

When anotherAppdomainThe current callcontext class generatesLogicalcallcontext. Only publicIlogicalthreadaffinativeInterface and stored inCallcontextObjects in are propagatedAppdomainExternal. The object that does not support this interface is notLogicalcallcontextThe instance is transmitted together with a remote method call.

It also emphasizes the role of remoting, but it can be imagined that basically callcontext uses a method similar to is ilogicalthreadaffinative to treat different objects differently. For those conforming to this interface, they will be placed in logicalcallcontext, otherwise.

From the perspective of the document, there seems to be no progress. At this time, I suddenly think of an interesting type of executioncontext that I have seen before. namespace is system. threading seems to have been prepared by multiple threads. However, the msdn example shows how to control the transfer of permission objects and does not talk about how to pass common objects.

I was wondering if the so-called logicalcallcontext exists in executioncontext? Check msdn and see the remarks:

ExecutioncontextClass provides a single container for all information related to the execution logic thread. This includes the security context, call context, and synchronization context.

ExecutioncontextClass allows the user code to capture and transmit the context between user-defined asynchronous points. The Common Language Runtime Library ensures consistent transmission of asynchronous points defined by the Runtime library within the managed processExecutioncontext.

the execution context is the managed equivalent of the com unit. In the application domain, the entire execution context must be transmitted every time a thread is transferred. In the thread .. ::. this occurs during transmission due to the start method, most thread pool operations, and Windows form thread sending through the windows message pump. Operate in an insecure thread pool (for example, unsafequeueuserworkitem method. Each time the stack is compressed, the managed entity, synchronization, Region settings, and user context flow. executioncontext class provides the capture and createcopy method to obtain the execution context and provide RUN to set the execution context of the current thread.

Associated with a threadExecutioncontextCannot be set on another thread. If you try this operation, an exception is thrown. ToExecutioncontextSpread from one thread to another. Please makeExecutioncontext.

ExecutioncontextInternal Storage andLogicalcallcontextAll associated data. This enables replication and transmission.ExecutioncontextTime PropagationLogicalcallcontextData.

Sure enough, the executioncontext contains logicalcallcontext data, and it is well illustrated that it is thread. start still uses the thread pool for most operations. executioncontext will automatically pass the data to those threads (about threadpool. the unsafequeueuerworkitem method should not be used by many people). It seems that all the actors are here, so we can now have a multi-thread show.

The first is to play a key role in exectioncontext. It may not be necessary in our code, but it is only because. the net class library method encapsulates this function for us. Without it, we only need to pass through the heap if we want to tell an object to another thread in one thread.

Secondly, logicalcallcontext, among the objects transmitted by executioncontext, is a lot of something that we cannot simply use (we cannot define a custom permission to spread an object ), logicalcallcontext is the best carrier for custom objects.

Finally, the question is how to read and write this logicalcallcontext, that is, the call for callcontext is finally made. Let's take a look at what callcontext has prepared for us: getdata, setdata, logicalgetdata, logicalsetdata, freenameddataslot, getheader, setheader, and hostcontext attributes.

The first focus is, of course, the getdata and setdata methods. After a simple test, we found that the two methods are indeed determined whether to send objects to new threads through the ilogicalthreadaffinative interface, the method for deleting this data is freenameddataslot. Now, you only need to add an empty interface to each object to be used in multiple threads, and set the object in the main thread before multithreading starts, then the problem can be solved after it is retrieved from other threads. After the multi-threaded part ends, do not forget to use freenameddataslot to delete it.

I don't know if you have noticed that, except getdata and setdata, There is a pair of logicalgetdata and logicalsetdata. What are the purposes of these two functions? Is it related to the logical of logicalcallcontext?

I did the previous simple experiment, but I used the logicalgetdata and logicalsetdata methods. The conclusion is whether or not the ilogicalthreadaffinative interface is implemented, objects can be accessed in the new thread, that is, any data can be transmitted to the new thread, including. net-defined basic types such as string and Int. This solution is almost perfect.

Let's look back at my task. You only need to modify appcontext. the implementation of the current attribute, and make a small process before and after the start of multithreading, other components can run on their respective threads in an intact concurrency.

This is the end of work.

Let's talk about what the callcontext. hostcontext attribute does. After a simple test, we found that in the Asp.net program, the hostcontext contains the httpcontext instance, and MS is also lazy. In fact, as long as Ms makes a small modification, Asp.net's multithreading does not need to be so troublesome. You only need httpcontext to implement the ilogicalthreadaffinative interface. No matter how many new threads are opened, you can access httpcontext from there. current, of course, Ms does not do this for a reason. Once httpcontext is propagated to other threads, it is difficult for Asp.net to control the lifecycle of the httpcontext object, the httpcontext object references this httprequest object, which may have much greater side effects than imagined.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.