Frage

I build an out-of-process cache for my webpage's database. Though when I try to do something with it (Set, Get), I get the following error:

A task was canceled

Here's my redis cache code. any help would be great. thanks

public class RedisCache : ICache
{
    private RedisConnection redis;

public RedisCache()
{
    redis = new RedisConnection("127.0.0.1");
    redis.Open();
}

public object Get(string key)
{
    var method = redis.Strings.Get(0, key);
    if (method == null)
        return null;
    BinaryFormatter bf = new BinaryFormatter();
    MemoryStream ms = new MemoryStream(method.Result);
    object obj = bf.Deserialize(ms);
    return obj;
}

public void Set(string key, object value)
{
    MemoryStream ms = new MemoryStream();
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(ms, value);
    redis.Strings.Set(0, key, ms.ToArray());
}

}

War es hilfreich?

Lösung

The "cancelled" status means that a message was queued but could not be written to the stream (for example, the stream never opened). From 1.3 onward, there are 2 main scenarios for this:

  • the message was queued because the connection was not open, and it was later discovered that the connection was impossible
  • a transaction was not issued because a pre-condition failed, or was aborted because "watch" key was changed

Since you aren't using transactions, it sounds like the connection couldn't be opened in the first place. You can check this by looking at the Task you get back from Open() - at the simplest:

redis.Wait(redis.Open());

The Wait method here is like the usual task.Wait(), but it has inbuilt timeout support, and a few other things to make life handy - I do encourage it's usage (mainly for convenience); likewise, redis.Wait(method) would be preferable to method.Result - but either will usually work fine. You could also await or ContinueWith the task - the key point here is that you need to check that it opened - and the only way to do that is by seeing what happens with the Task.

Note that the connection has some events for detecting failure (errors and closure). You may also find it conveneint to open the connection with ConnectionUtils, which has some inbuilt handling for a range of common scenarios.

On final observation: BinaryFormatter ... you may find when you version / refactor your API you can't load your old data - don't say I didn't warn you ;p I would recommend any contract based serializer instead: XmlSerializer, DataContractSerializer, JSON.NET, or protobuf-net (the latter being dense binary - ideal for opaque out-of-process BLOB such as redis, although I hear the author is nothing but trouble).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top